1

I have a dictionary of states (example IA:Idaho). I have loaded the dictionary into a DataFrame bystate_df.

then I am importing a CSV with states deaths that I want to add them to the bystate_df as I read the lines:

byState_df = pd.DataFrame(states.items())
byState_df['Deaths'] = 0
df['Deaths'] = df['Deaths'].convert_objects(convert_numeric=True)
print byState_df
for index, row in df.iterrows():
    if row['Area'] in states:
           byState_df[(byState_df[0] == row['Area'])]['Deaths'] = row['Deaths']         

print byState_df

but the byState_df is still 0 afterwords:

      0                         1  Deaths
 0   WA                Washington       0
 1   WI                 Wisconsin       0
 2   WV             West Virginia       0
 3   FL                   Florida       0
 4   WY                   Wyoming       0
 5   NH             New Hampshire       0
 6   NJ                New Jersey       0
 7   NM                New Mexico       0
 8   NA                  National       0

I test row['Deaths'] while it iterates and it's producing the correct values, it just seem to be setting the byState_df value incorrectly.

2
  • I think it's because you use chained slice in byState_df[(byState_df[0] == row['Area'])]['Deaths'] so that you are actually setting some values on a copy rather than the actual df. Commented Jul 21, 2015 at 17:33
  • The first index [...==...] is advanced indexing, and produces a copy. Indexing with ['Deaths'] first might work, since it returns a view of one of the fields. Commented Jul 21, 2015 at 19:07

1 Answer 1

1

Can you try the following code where I use .loc instead of [][].

byState_df = pd.DataFrame(states.items())
byState_df['Deaths'] = 0
df['Deaths'] = df['Deaths'].convert_objects(convert_numeric=True)
print byState_df
for index, row in df.iterrows():
    if row['Area'] in states:
           byState_df.loc[byState_df[0] == row['Area'], 'Deaths'] = row['Deaths']         

print byState_df
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.