I have a column in a DataFrame
, which I want to change the values of.
Calling the DataFrame
df
, and supposing one column is labelled A
,
I'm doing:
df.A = df.A.map(lambda x: -x)
This results in the operation actually being done, however it also results in the following Warning:
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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self[name] = value
OK, then I try with what is suggested in the Warning, and write:
df.loc[:,'A'] = df.A.map(lambda x: -x)
Only to get the exact same warning
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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self.obj[item] = s
OK, the last line is slightly different, but I don't know how to interpret it.
Why am I getting the SettingWithCopyWarning
even when I'm using .loc
, as requested?
Then, I've tried a third method:
- create a new column with the data
- drop the old column
- rename the new column with the old name
``
df['new'] = df.A.map(lambda x: -x)
df.drop('A',axis=1,inplace=True)
df.rename(columns={'new':'A'},inplace=True)
And again! I still get the warning:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
return super().rename(
At this point, I don't understand what is the proper way to replace a column with other values? Am I missing some important aspect of the framework? I just shouldn't try to use an existing column name for other data?