0

The following code produce this warning: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.

self.df_rankpct["rankpct_market_value"] = self.df_rankpct.groupby(['Date'])[
                "market_value"].rank( method ="min")

How can I avoid the warning?

Pablo Vilas
  • 546
  • 5
  • 13
  • 1
    is `df_rankpct` derived from another dataframe? if yes put a `.copy()` to the code where you define `df_rankpct` – anky Dec 29 '20 at 09:27
  • Does this answer your question? [How to deal with SettingWithCopyWarning in Pandas](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – William Baker Morrison Dec 29 '20 at 09:41
  • No, my problem is not solved using df.loc . See anky answers – Pablo Vilas Dec 29 '20 at 11:09

1 Answers1

1

There are a couple of workarounds:

1: Modify warning

If you want to switch of the warning since its not an error, set

pd.set_option('mode.chained_assignment', xxx)

replace xxx with 'raise' (to raise an exception instead of a warning), 'warn'(to generate default warning), None (to switch off the warning entirely)

2: Modify is_copy

Pandas DataFrame has an is_copy property that is None by default but uses a weakref, by setting is_copy to None, this warning can be avoided.

self.df_rankpct.is_copy = None

3: Use loc to slice subsets

self.df_rankpct.loc[:, ['rankpct_market_value']] = self.df_rankpct.groupby(['Date'])["market_value"].rank( method ="min")

Please refer to these links:

https://www.dataquest.io/blog/settingwithcopywarning/

How to deal with SettingWithCopyWarning in Pandas

Snehal Nair
  • 181
  • 1
  • 6