Michael Qiao
Michael Qiao

Reputation: 71

Can't update values in Pandas dataframe when NaN values present

Say I have the code here

df = pd.DataFrame([[10,20], [30, 40], [50, 60]],
     columns=['max_speed', 'shield'])

it outputs

   max_speed  shield
0         10      20
1         30      40
2         50      60

Changing a value here, I can easily do

df.iloc[1]['shield'] = 5 

outputting

   max_speed  shield
0         10      20
1         30       5
2         50      60

However, if there are NaN values present in the dataframe, I can't change the values anymore.

df = pd.DataFrame([[10], [30, 40], [50, 60]],
     columns=['max_speed', 'shield'])
   max_speed  shield
0         10     NaN
1         30    40.0
2         50    60.0
df.iloc[1]['shield'] = 5 
   max_speed  shield
0         10     NaN
1         30    40.0
2         50    60.0

I understand I can use fillna() and others, but would like to know in this particular case what I can do. I want to fill a larger dataset's NaN values with the next rows value where I don't think these can help me e.g. [0]['shield'] = 40

Upvotes: 1

Views: 1300

Answers (1)

Davide Anghileri
Davide Anghileri

Reputation: 901

The problem is the chained assignement. Please read more here.

To avoid this simply put the chained operations into a single operation like:

df.loc[1, 'shield'] = 5 

Upvotes: 3

Related Questions