0

This is my dataframe example:

|  A  |  B  |
|:----|:----|
|  1  |  LA |
|  2  |None |
|NaN  |  TX |

I only want to fill the null values for the last row with the max value of the column.

example.iloc[-1]['A'] = example['A'].max()

The code above does not change the NaN value.

smci
  • 32,567
  • 20
  • 113
  • 146
Claire_L
  • 13
  • 1
  • 6
  • This fails with a `SettingWithCopyWarning` because `example.iloc[-1]` then `['A']` is a slice of a slice, which makes a copy. Instead, you want to index all in one `.iloc[]`/`.loc[]` expression, not multiple chained slices. – smci Aug 05 '21 at 22:24
  • @smci Gotcha. Thanks! – Claire_L Aug 06 '21 at 00:46
  • That's a really good explanation. – Claire_L Aug 06 '21 at 00:53
  • Admittedly it's an annoying pandas limitation that you can't mix `.iloc[]` numbered indexing (e.g. of rows) with `.loc[]` named indexing (of columns). So you just have to use `.iloc[]` numbered indexing. – smci Aug 06 '21 at 03:49

1 Answers1

0

Is it what you expect?

>>> df['A'].fillna(df['A'].max())
0    1.0
1    2.0
2    2.0
Name: A, dtype: float64

With your code, you have probably a SettingWithCopyWarning message?

You can use also:

df.iloc[-1, df.columns.get_loc('A')] = df['A'].max()
print(df)

     A     B
0  1.0    LA
1  2.0  None
2  2.0    TX
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Yes, I did get the warning. The second one works better for my situation! I need to modify each cell in the last row with the same logic. Thanks a lot! – Claire_L Aug 06 '21 at 00:48