Python pandas 删除 SettingWithCopyWarning

标签 python pandas pattern-matching

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

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

我用这样的代码填充它,它在 df.Matrix 中找到包含“Good”、“Bad”值的字符串,并用 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]

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

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\0\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]

到目前为止,我正在使用

抑制代码
pd.options.mode.chained_assignment = None

如果我不抑制错误消息,我将收到大约 20 条错误消息。有没有其他格式我可以更改数据,这样我就不会收到错误消息?

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

最佳答案

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

Pandas: Chained assignments

您确定这就是您的全部代码吗?请展示你在做什么。

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]

第二个例子

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]

关于Python pandas 删除 SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21560749/

相关文章:

python - 如何将选择动态传递到 Django 表单中

python - Pandas DataFrame Groupby 获取唯一行条件并识别增加值直至组数

python - 在 pandas DataFrame 的每一列中找到第一个非零值

python - 如何从日期时间推断季度?

c - 如何从 LBP 图像中获取 256 个 bins/pixels?

php - Mysql查询找不到第一个词

python - 使用 SQLAlchemy 添加多对多关系

python-3.x - 来自 Flask 中 FileStorage 的 Pandas read_csv

python - 在 Pandas.read_excel 中使用转换器时可以使用列索引吗

json - 使用 Shell 脚本从 JSON 字符串获取 JSON 值