Possible spurious SettingWithCopyWarning · Issue #6757 · pandas-dev/pandas (original) (raw)
Found some SettingWithCopyWarning
warnings in older code with newer pandas. But it's quite possible that these are just side-effects of the warning ('False positives') and it cannot easily be detected, but I am no expert in that field.
Simplified dummy example:
In [1]: df = pd.DataFrame(np.arange(20).reshape(5, 4), columns=list('ABCD'))
In [2]: df
Out[2]:
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
# reassign a selection to df
In [3]: df = df[(df['A']%5)!=0]
Setting a value with .loc[]
(this output is from master, in 0.13.1 I got even the advice to Try using .loc[row_index,col_indexer] = value instead
while I was using it ... in master just the warning):
In [4]: df.loc[df['B']==17, 'C'] = 1000
C:\Anaconda\envs\devel\Scripts\ipython-script.py:1: SettingWithCopyWarning: A va
lue is trying to be set on a copy of a slice from a DataFrame
#!C:\Anaconda\envs\devel\python.exe
And then replacing a value with replace
(also here the advice to use .loc
is a little bit strange I think):
In [5]: df['D'] = df['D'].replace({7:2000})
C:\Anaconda\envs\devel\Scripts\ipython-script.py:1: SettingWithCopyWarning: A va
lue is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
#!C:\Anaconda\envs\devel\python.exe
In [6]: df
Out[6]:
A B C D
1 4 5 6 2000
2 8 9 10 11
3 12 13 14 15
4 16 17 1000 19