0

I tried filling the NA values of a column in a dataframe with:

df1 = data.copy()
df1.columns = data.columns.str.lower()
df2 = df1[['passangerid', 'trip_cost','class']]
df2['class'] = df2['class'].fillna(0)
df2

Although getting this error:

:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation:

df2['class'] = df2['class'].fillna(0, axis = 0)

Can someone please help?

David Thery
  • 669
  • 1
  • 6
  • 21
  • 1
    in addition to dm2's answer, see this SO post for more details: [How to deal with SettingWithCopyWarning in Pandas](https://stackoverflow.com/q/20625582/13138364) – tdy May 02 '21 at 13:15

1 Answers1

2

First of all I'd advise you to follow the warning message and read up on the caveats in the provided link.

You're getting this warning (not an error) because your df2 is a slice of your df1, not a separate DataFrame.

To avoid getting this warning you can use .copy() method as:

df2 = df1[['passangerid', 'trip_cost','class']].copy()
dm2
  • 4,053
  • 3
  • 17
  • 28