Home > Enterprise >  Avoid raising Setting with copy warning
Avoid raising Setting with copy warning

Time:02-04

Suppose I have a dataframe df with columns a, b, c, d and I want to subtract mean of the columns from columns a,b,d. How do I achieve the same?

I have tried df[['a','b','d']] = df[['a','b','d']] - df[['a','b','d']].mean() but I get SettingWithCopyWarning. How do I achieve the same without the warning?

CodePudding user response:

df[['a','b','d']] is a like view of original dataframe...trying to set values in a view may or may not work everytime

do it seperately

df['a']=df['a'].mean()
df['b']=df['b'].mean()
df['d']=df['d'].mean()

its doesn't make much difference in performance

CodePudding user response:

Are you sure you're getting the warning at that statement/line ?

Anyways, In a Pandorable way and to reduce visible noise, I would do :

cols = ["a", "b", "d"]

df[cols] = df[cols].sub(df[cols].mean())
  • Related