python pandas 0.16:SettingWithCopyWarning错误报告

时间:2015-06-25 16:55:36

标签: python pandas

根据我的另一个问题: Python Anaconda: how to test if updated libraries are compatible with my existing code?

我诅咒那天我被迫升级为熊猫0.16。 其中一件我不明白的事情就是为什么当我做一些平庸的事情时,我会得到一个链式赋值警告,就像在现有数据帧中添加一个新字段并用1初始化它一样:

mydataframe['x']=1

导致以下警告:

  

SettingWithCopyWarning:尝试在a的副本上设置值   从DataFrame切片。尝试使用.loc [row_indexer,col_indexer] =   代替值

     

请参阅文档中的警告:   http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy   mydataframe [ 'X'] = 1

我知道在为数据帧的副本分配值时可能会出现问题,但在这里我只是向数据帧添加一个新字段!我该如何更改我的代码(在以前的熊猫版本中完美运行)?

2 个答案:

答案 0 :(得分:1)

Here's an attempt at an answer, or at least an attempt to reproduce the message. (Note that you may only get this message once and might need to start a new shell or do %reset in ipython to get this message.)

In [1]: %reset

Once deleted, variables cannot be recovered. Proceed (y/[n])? y

In [2]: import pandas as pd

In [3]: pd.__version__
Out[3]: '0.16.0'

Here are 3 variations of setting a new column to '1'. The first two do not generate the warning, but the third one does. (Second one thanks to @Jeff's suggestion)

In [4]: df = pd.DataFrame({ 'x':[1,2,3], 'y':[77,88,99] })
   ...: df['z'] = 1

In [5]: df = pd.DataFrame({ 'x':[1,2,3], 'y':[77,88,99] })
   ...: df = df[1:]
   ...: df['z'] = 1

In [6]: df = pd.DataFrame({ 'x':[1,2,3], 'y':[77,88,99] })
   ...: df2 = df[1:]
   ...: df2['z'] = 1

-c:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable
/indexing.html#indexing-view-versus-copy

Perhaps others can correct me if I'm wrong, but I believe the error message here is relating to df2 being a copy of a slice of df. However, that's not really an issue as the resulting df and df2 are what I would have expected:

In [7]: df
Out[7]: 
   x   y
0  1  77
1  2  88
2  3  99

In [8]: df2
Out[8]: 
   x   y  z
1  2  88  1
2  3  99  1

I know this is going to be terrible to say, but when I get that message I just check to see whether the command did what I wanted or not and don't overly think about the warning. But whether you get a warning message or not, checking that a command did what you expected is really something you need to do all the time in pandas (or matlab, or R, or SAS, or Stata, ... )

答案 1 :(得分:0)

这不会产生警告:

df = pd.DataFrame({ 'x':[1,2,3], 'y':[77,88,99] })
df2 = df[1:].copy()
df2['z'] = 1