Pandas SettingWithCopyWarning When Using loc

自闭症网瘾萝莉.ら 提交于 2020-01-03 08:34:28

问题


Have a general question on assignments with indexing/slicing using .loc.

Assume the below DataFrame, df:

df:    
    A   B   C
0   a   b   
1   a   b   
2   b   a   
3   c   c   
4   c   a   

code to reproduce:

df = pd.DataFrame({'A':list('aabcc'), 'B':list('bbaca'), 'C':5*[None]})

I create df1 using:

df1=df.loc[df.A=='c']

df1:
    A   B   C
3   c   c   
4   c   a   

I then assign a value to C based upon a value in B using:

df1.loc[df1.B=='a','C']='d'

The assignment works, but I receive a SettingWithCopy warning. Am I doing something wrong or is this the expected functionality? I thought that using .loc would avoid chained assignment. Is there something that I am missing? I am using Pandas 14.1


回答1:


@EdChum answer in comments to OP has solved the issue. i.e. replace

df1=df.loc[df.A=='c']

with

df1=df.loc[df.A=='c'].copy()

this will make it clear your intentions and not raise a warning



来源:https://stackoverflow.com/questions/25489875/pandas-settingwithcopywarning-when-using-loc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!