12

I have a Pandas DataFrame and I would like to change all the values of a column with this code:

df["Population"] = round(df["Population"]/1000000,1)

And I receive the following warning:

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(
<ipython-input-6-59bf041bb022>:2: 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
  df["Population"] = round(df["Population"]/1000000,1)

What would be the correct way to do it and avoid such warning?

Thank you for your help!

idejuan
  • 461
  • 2
  • 4
  • 11

1 Answers1

12

Before you have your df , it is subset of some other dataframe

df = alldf[cond].copy()

Or we try assign

df = df.assign(Population = round(df["Population"]/1000000,1))
BENY
  • 317,841
  • 20
  • 164
  • 234
  • 2
    Thank you. Solution 2 you suggested has worked. Nevertheless, I have found out why the error was happening in the first place. I was working on a copy of the dataframe, because in a previous line I was assigning df to a copy. I found the solution thanks to this post https://stackoverflow.com/questions/33727667/pandas-settingwithcopywarning-a-value-is-trying-to-be-set-on-a-copy-of-a-slice – idejuan Nov 23 '20 at 12:52
  • 1
    This is a valuable resource o understand the underlying issue: https://towardsdatascience.com/explaining-the-settingwithcopywarning-in-pandas-ebc19d799d25 – idejuan Nov 23 '20 at 22:19