Python pandas 删除 SettingWithCopyWarning

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21560749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:39:44  来源:igfitidea点击:

Python pandas removing SettingWithCopyWarning

pythonpandaspattern-matching

提问by user3084006

So I made an empty dataframe using

所以我使用了一个空的数据框

df=data[['ID','Matrix','Name','Country', 'Units']]
df['Value']=''

and I am filling it in with code like this, which finds strings containing values of 'Good', 'Bad' in df.Matrixand filling them with values in sch[i]:

我用这样的代码填充它,它找到包含“好”、“坏”值的字符串,df.Matrix并用值填充它们sch[i]

df.loc[df.Matrix.str.contains('Good'),'Value'] = sch[2]
df.loc[df.Matrix.str.contains('Bad'),'Value'] = sch[6]
df.loc[df.Matrix.str.contains('Excellent'),'Value'] = sch[8]

I have been getting a bunch of errors like both of these two different ones:

我收到了一堆错误,例如这两个不同的错误:

C:\Python33\lib\site-packages\pandas\core\strings.py:184: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
  " groups, use str.extract.", UserWarning)

C:\Users
pd.options.mode.chained_assignment = None
\Desktop\python\Sorter.py:57: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame df.loc[df.Matrix.str.contains('Bad'),'Value'] = sch[6]

So far I am suppressing the code using

到目前为止,我正在使用

In [13]: df = DataFrame(index=range(5))

In [14]: df['Value'] = ''

In [15]: df.loc[[1,4],'Value'] = 'bad'

In [16]: df.loc[[0,3],'Value'] = 'good'

In [17]: df
Out[17]: 
  Value
0  good
1   bad
2      
3  good
4   bad

[5 rows x 1 columns]

If I do not suppress the error messages I will get about 20 of them. Is there another format I can change the data so that I do not get the error message?

如果我不抑制错误消息,我将收到大约 20 条错误消息。是否有另一种格式可以更改数据以便我不会收到错误消息?

I am using python 3 and pandas 0.131 if it helps

如果有帮助,我正在使用 python 3 和 pandas 0.131

回答by Jeff

Here is a good explanation of why this warning was turned on:

这里很好地解释了为什么打开这个警告:

Pandas: Chained assignments

Pandas:链式赋值

Are you sure that is all of your code? Pls show all of what you are doing.

你确定这是你的全部代码吗?请展示您正在做的所有事情。

In [1]: df = DataFrame(index=range(5))

In [2]: df['Value'] = ''

In [3]: df2 = DataFrame(dict(A=['foo','foo','bar','bar','bah']))

In [4]: df
Out[4]: 
  Value
0      
1      
2      
3      
4      

[5 rows x 1 columns]

In [5]: df2
Out[5]: 
     A
0  foo
1  foo
2  bar
3  bar
4  bah

[5 rows x 1 columns]

In [6]: df.loc[df2.A.str.contains('foo'),'Value'] = 'good'

In [7]: df.loc[df2.A.str.contains('bar'),'Value'] = 'bad'

In [8]: df
Out[8]: 
  Value
0  good
1  good
2   bad
3   bad
4      

[5 rows x 1 columns]

2nd example

第二个例子

##代码##