本文介绍了使用loc时的Pandas SettingWithCopyWarning的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.loc对索引/切片的赋值进行一般性提问。

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

假设下面的DataFrame,df:

Assume the below DataFrame, df:

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

要重现的代码:

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

我使用以下方式创建df1:

I create df1 using:

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

df1:
    A   B   C
3   c   c
4   c   a

然后我根据B中的值使用以下内容为C赋值:

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

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

作业工作,但我收到一个SettingWithCopy警告。我做错了什么或者这是预期的功能吗?我认为使用.loc会避免链接赋值。有什么东西我不见了吗?我正在使用Pandas 14.1

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

推荐答案

@EdChum在评论中回答OP已经解决了这个问题。
即替换

@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()



这篇关于使用loc时的Pandas SettingWithCopyWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:36