1

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

  • While I can't exactly explain why this is happening, `df.loc[1, 'shield'] = 5 ` will do the trick. – mlang Nov 14 '20 at 12:49
  • Does this answer your question? [Set value for particular cell in pandas DataFrame using index](https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index) – Quickbeam2k1 Nov 14 '20 at 12:53

1 Answers1

3

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