Home > OS >  'value trying to be set on copy' warning
'value trying to be set on copy' warning

Time:06-04

I'm trying to do a simple replacement of values in multiple columns of a dataframe with the .loc function, using this this code

df.loc[:,'Q014':'Q032'] = 
df.loc[:,'Q014':'Q032'].replace({'a':1,'b':0})

I don't understand why I get this warning

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

I've read the documentation but I cannot see what the problem is. Someone please help me to understand. Cheers

CodePudding user response:

The following article explains clearly. Please refer https://www.analyticsvidhya.com/blog/2021/11/3-ways-to-deal-with-settingwithcopywarning-in-pandas/

If your code is working as intended, you could turn off the warning by pd.options.mode.chained_assignment = None.

Edit: I am unable to leave comments hence posting in the answer section.

CodePudding user response:

It's not possible to answer your question with this single line because your code can't trigger SettingWithCopyWarning as it. It happens probably earlier in your code.

cols = [f'Q{i:03}' for i in range(1, 50)]
vals = np.random.choice(['a', 'b'], (10, len(cols)))
df = pd.DataFrame(vals, columns=cols)

df.loc[:,'Q014':'Q032'] = df.loc[:,'Q014':'Q032'].replace({'a':1,'b':0})

Output:

>>> df.loc[:, 'Q014':'Q032']
  Q014 Q015 Q016 Q017 Q018 Q019 Q020 Q021 Q022 Q023 Q024 Q025 Q026 Q027 Q028 Q029 Q030 Q031 Q032
0    1    0    0    0    1    0    1    1    1    0    0    0    1    0    1    0    0    1    0
1    1    0    1    0    1    0    0    0    0    0    0    0    0    1    0    0    0    1    1
2    1    1    1    0    1    1    0    0    0    1    0    0    0    0    0    0    0    1    0
3    1    0    1    0    0    1    0    0    1    0    1    0    1    0    1    1    1    1    0
4    0    1    0    0    0    0    0    0    1    0    1    1    0    1    1    0    0    0    0
5    0    1    0    1    1    1    0    0    0    1    1    1    0    1    1    1    1    1    1
6    0    0    0    0    0    0    0    1    1    1    0    0    0    1    0    1    1    0    1
7    1    1    0    0    0    1    1    1    0    0    0    1    1    1    1    1    0    1    1
8    1    0    0    0    1    0    1    1    1    0    0    1    1    0    1    1    1    1    0
9    0    1    1    0    0    0    0    1    1    0    1    1    1    1    1    1    1    0    0
  • Related