Python pandas删除了SettingWithCopyWarning

use*_*006 6 python pattern-matching pandas

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

df=data[['ID','Matrix','Name','Country', 'Units']]
df['Value']=''
Run Code Online (Sandbox Code Playgroud)

我用这样的代码填充它,它找到包含'Good','Bad'值的字符串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]
Run Code Online (Sandbox Code Playgroud)

我遇到了一堆像这两个不同的错误:

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]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我正在使用压缩代码

pd.options.mode.chained_assignment = None
Run Code Online (Sandbox Code Playgroud)

如果我不压制错误消息,我将得到大约20个错误消息.是否有其他格式我可以更改数据,以便我不会收到错误消息?

我使用python 3和pandas 0.131如果它有帮助

Jef*_*eff 7

这里有一个很好的解释为什么这个警告被打开:

熊猫:链式作业

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

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]
Run Code Online (Sandbox Code Playgroud)

第二个例子

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]
Run Code Online (Sandbox Code Playgroud)

  • 最好的方法是创建系列,然后直接分配它,例如``df ['Value'] = s``,而不是将其创建为空并覆盖值.只需根据需要创建系列; 大熊猫将对齐它(用nan填充剩余的值) (3认同)