背景

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

当前回答

由于这个问题已经在现有的答案中得到了充分的解释和讨论,因此我将提供一种简洁的使用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,但它没有。熊猫魔法)。

其他回答

由于这个问题已经在现有的答案中得到了充分的解释和讨论,因此我将提供一种简洁的使用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,但它没有。熊猫魔法)。

只需在警告出现之前使用.copy()方法创建数据帧的副本,以删除所有警告。

之所以会发生这种情况,是因为我们不想对原始的quote_df进行更改。换句话说,我们不想使用为quote_df创建的quote_df对象的引用。

quote_df = quote_df.copy()

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

在切片后创建.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,仍然会得到相同的警告。误导?是的。烦人吗?你的赌注。有用吗?可能,当使用链式赋值时。但是它不能正确地检测链赋值,并且不加区别地输出警告。

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

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

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

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

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

在我的情况下,我会基于索引创建一个新列,但我得到了与您相同的警告:

df_temp["Quarter"] = df_temp.index.quarter

我使用insert()而不是直接赋值,它为我工作:

df_temp.insert(loc=0, column='Quarter', value=df_temp.index.quarter)