背景

我刚刚把我的熊猫从0.11升级到0.13.0rc1。现在,应用程序弹出了许多新的警告。其中一个是这样的:

E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE

我想知道这到底是什么意思?我需要改变什么吗?

如果我坚持使用quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE,我应该如何暂停警告?

给出错误的函数

def _decode_stock_quote(list_of_150_stk_str):
    """decode the webpage and return dataframe"""

    from cStringIO import StringIO

    str_of_all = "".join(list_of_150_stk_str)

    quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
    quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
    quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
    quote_df['TClose'] = quote_df['TPrice']
    quote_df['RT']     = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1)
    quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
    quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
    quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19)
    quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312')
    quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
    
    return quote_df

更多错误消息

E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TVol']   = quote_df['TVol']/TVOL_SCALE
E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TAmt']   = quote_df['TAmt']/TAMT_SCALE
E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  quote_df['TDate']  = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])

当前回答

对我来说奏效了:

import pandas as pd
# ...
pd.set_option('mode.chained_assignment', None)

其他回答

当我执行这部分代码时,我也遇到了同样的警告:

def scaler(self, numericals):
    scaler = MinMaxScaler()
    self.data.loc[:, numericals[0]] = scaler.fit_transform(self.data.loc[:, numericals[0]])
    self.data.loc[:, numericals[1]] = scaler.fit_transform(self.data.loc[:, numericals[1]])

其中标量是一个MinMaxScaler和数字[0]包含三个我的数字列的名字。

当我将代码更改为:

def scaler(self, numericals):
    scaler = MinMaxScaler()
    self.data.loc[:][numericals[0]] = scaler.fit_transform(self.data.loc[:][numericals[0]])
    self.data.loc[:][numericals[1]] = scaler.fit_transform(self.data.loc[:][numericals[1]])

因此,只需将[:,~]改为[:][~]。

这可能只适用于NumPy,这意味着你可能需要导入它,但我为示例NumPy使用的数据在计算中不是必需的,但你可以简单地通过使用下面这一行代码来停止这个设置和复制警告消息:

np.warnings.filterwarnings('ignore')

有些人可能只是想压制这个警告:

class SupressSettingWithCopyWarning:
    def __enter__(self):
        pd.options.mode.chained_assignment = None

    def __exit__(self, *args):
        pd.options.mode.chained_assignment = 'warn'

with SupressSettingWithCopyWarning():
    #code that produces warning

这里我直接回答这个问题。我们该如何应对呢?

在切片后创建.copy(deep=False)。看到pandas.DataFrame.copy。

等等,切片不是会返回副本吗?毕竟,这就是警告信息试图表达的意思?阅读长答案:

import pandas as pd
df = pd.DataFrame({'x':[1,2,3]})

这给出了一个警告:

df0 = df[df.x>2]
df0['foo'] = 'bar'

这不是:

df1 = df[df.x>2].copy(deep=False)
df1['foo'] = 'bar'

df0和df1都是DataFrame对象,但它们的某些不同之处使pandas能够打印警告。让我们来看看它是什么。

import inspect
slice= df[df.x>2]
slice_copy = df[df.x>2].copy(deep=False)
inspect.getmembers(slice)
inspect.getmembers(slice_copy)

使用你选择的diff工具,你会发现除了几个地址之外,唯一的实质性区别是:

|          | slice   | slice_copy |
| _is_copy | weakref | None       |

决定是否警告的方法是DataFrame。_check_setitem_copy检查_is_copy。给你。做一个拷贝,这样你的DataFrame就不是_is_copy。

警告建议使用.loc,但如果您在_is_copy的帧上使用.loc,仍然会得到相同的警告。误导?是的。烦人吗?你的赌注。有用吗?可能,当使用链式赋值时。但是它不能正确地检测链赋值,并且不加区别地输出警告。

对我来说,这个问题发生在下面一个简化的例子中。我也能够解决它(希望有一个正确的解决方案):

带有警告的旧代码:

def update_old_dataframe(old_dataframe, new_dataframe):
    for new_index, new_row in new_dataframe.iterrorws():
        old_dataframe.loc[new_index] = update_row(old_dataframe.loc[new_index], new_row)

def update_row(old_row, new_row):
    for field in [list_of_columns]:
        # line with warning because of chain indexing old_dataframe[new_index][field]
        old_row[field] = new_row[field]
    return old_row

输出old_row[field] = new_row[field]行的警告

因为update_row方法中的行实际上是Series类型,所以我将行替换为:

old_row.at[field] = new_row.at[field]

例如,用于访问/查找一个Series的方法。尽管两者都工作得很好,结果是相同的,这样我就不必禁用警告(=保留它们用于其他地方的其他链索引问题)。