Python Forum
Iterating through rows and saving result in a new column
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterating through rows and saving result in a new column
#3
(Apr-20-2017, 04:46 PM)kiton Wrote: To create a new column with identifed FIPS code, I do the following:

for index, row in df.iterrow():
     df["FIPS"] = df[stateplane.identify('lon', 'lat', fmt='fips')]

This code contains quite big amount of errors. Iterating over df.iterrows() (not df.iterrow()) means iterating over pairs (index, row) as you correctly use in for clausule, but you dont use it at all in the body of the loop...  steteplane.identify() seems to accept only numerical arguments for longitude and latitude, not 'lon' and 'lat' strings (it cant know that these should be substitued with values of appropriate row of dataframe). Morever indexing dataframe with returning value of identify would almost never work, neither trying to assign it to a new df column.

It is possible to rewrite your for loop to work as you want:
df['FIPS'] = 0  # dummy value
for index, row in df.iterrows():
    df['FIPS'][index] = stateplane.identify(row['lon'], row['lat'], fmt='fips')
But standard (and more effective) way to apply some function over dataframe columns or rows is to use .apply():
df['fips'] = df.apply(lambda row: stateplane.identify(row['lon'], row['lat'], fmt='FIPS'), axis=1)
Reply


Messages In This Thread
RE: Iterating through rows and saving result in a new column - by zivoni - Apr-20-2017, 06:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  This result object does not return rows. It has been closed automatically dawid294 6 1,808 Mar-30-2024, 03:08 AM
Last Post: NolaCuriel
  Saving the print result in a text file Calli 8 2,169 Sep-25-2022, 06:38 PM
Last Post: snippsat
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 980 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,708 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  Iterating Through Data Frame Rows JoeDainton123 2 3,055 Aug-09-2021, 07:01 AM
Last Post: Pedroski55
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,210 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 7,593 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  How to filter out Column data From Multiple rows data? firaki12345 10 5,435 Feb-06-2021, 04:54 AM
Last Post: buran
  how to combine rows to a column base on ids zhujp98 0 1,570 Nov-03-2020, 04:10 PM
Last Post: zhujp98
  How to generate rows based on values in a column to fill missing values codesmatter 1 2,214 Oct-31-2020, 12:05 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020