背景

我刚刚把我的熊猫从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])

当前回答

如果你已经将切片分配给一个变量,并希望像下面这样使用变量进行设置:

df2 = df[df['A'] > 2]
df2['B'] = value

如果你不想使用Jeff的解,因为你计算df2的条件太长或其他原因,那么你可以使用以下方法:

df.loc[df2.index.tolist(), 'B'] = value

df2.index.tolist()返回df2中所有条目的索引,这些索引将用于设置原始数据框架中的列B。

其他回答

由于这个问题已经在现有的答案中得到了充分的解释和讨论,因此我将提供一种简洁的使用pandas的上下文管理器方法。Option_context(链接到文档和示例)-绝对没有必要创建一个带有所有dunder方法和其他花哨功能的自定义类。

首先是上下文管理器代码本身:

from contextlib import contextmanager

@contextmanager
def SuppressPandasWarning():
    with pd.option_context("mode.chained_assignment", None):
        yield

然后是一个例子:

import pandas as pd
from string import ascii_letters

a = pd.DataFrame({"A": list(ascii_letters[0:4]), "B": range(0,4)})

mask = a["A"].isin(["c", "d"])
# Even shallow copy below is enough to not raise the warning, but why is a mystery to me.
b = a.loc[mask]  # .copy(deep=False)

# Raises the `SettingWithCopyWarning`
b["B"] = b["B"] * 2

# Does not!
with SuppressPandasWarning():
    b["B"] = b["B"] * 2

值得注意的是,这两种方法都不修改a,这让我有点惊讶,即使是带有.copy(deep=False)的浅df复制也会防止引发这个警告(据我所知,浅复制至少也应该修改a,但它没有。熊猫魔法)。

后续初学者问题/备注

也许这是对像我这样的初学者的澄清(我来自R,它的工作原理似乎有点不同)。以下看起来无害的功能代码不断产生SettingWithCopy警告,我不知道为什么。我已经阅读并理解了“链式索引”,但我的代码不包含任何:

def plot(pdb, df, title, **kw):
    df['target'] = (df['ogg'] + df['ugg']) / 2
    # ...

但是后来,太迟了,我查看了plot()函数被调用的地方:

    df = data[data['anz_emw'] > 0]
    pixbuf = plot(pdb, df, title)

所以"df"不是一个数据帧,而是一个对象,它以某种方式记住它是通过索引一个数据帧创建的(这是一个视图吗?)这将使plot()中的行,

 df['target'] = ...

相当于

 data[data['anz_emw'] > 0]['target'] = ...

这是链式索引。

不管怎么说,

def plot(pdb, df, title, **kw):
    df.loc[:,'target'] = (df['ogg'] + df['ugg']) / 2

固定它。

创建SettingWithCopyWarning是为了标记可能令人困惑的“链式”赋值,例如下面的赋值,它并不总是像预期的那样工作,特别是当第一个选择返回一个副本时。[背景讨论见GH5390和GH5597。]

df[df['A'] > 2]['B'] = new_val  # new_val not set in df

该警告提供了重写建议如下:

df.loc[df['A'] > 2, 'B'] = new_val

然而,这并不符合你的用法,这相当于:

df = df[df['A'] > 2]
df['B'] = new_val

虽然很明显,您并不关心写入操作是否使其返回到原始帧(因为您正在覆盖对它的引用),但不幸的是,此模式无法与第一个链式赋值示例区分开来。因此出现了(假阳性)警告。如果您想进一步阅读,在索引文档中讨论了假阳性的可能性。您可以使用以下赋值安全地禁用此新警告。

import pandas as pd
pd.options.mode.chained_assignment = None  # default='warn'

其他资源

pandas用户指南:索引和选择数据 Python数据科学手册:数据索引和选择 真正的Python: SettingWithCopyWarning在Pandas:视图vs副本 Dataquest: SettingwithCopyWarning:如何修复此警告在熊猫 走向数据科学:解释熊猫中copywarning的设置

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

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]])

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

这应该可以工作:

quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE