Python:SettingWithCopyWarning:试图在 DataFrame 的切片副本上设置值

Python: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

我的 pandas 数据框:

dframe = pd.DataFrame({"A":list("abcde"), "B":list("aabbc"), "C":[1,2,3,4,5]},  index=[10,11,12,13,14])

    A   B   C
10  a   a   1
11  b   a   2
12  c   b   3
13  d   b   4
14  e   c   5

我想要的输出:

    A   B   C   a   b   c
10  a   a   1   1   None    None
11  b   a   2   2   None    None
12  c   b   3   None    3   None
13  d   b   4   None    4   None
14  e   c   5   None    None    5

想法是根据 'B' 列中的值创建新列,复制 'C' 列中的相应值并将它们粘贴到新创建的列中。 这是我的代码:

lis = sorted(list(dframe.B.unique()))

#creating empty columns
for items in lis:
   dframe[items] = None


 #here copy and pasting
    for items in range(0, len(dframe)):
        slot = dframe.B.iloc[items]
        dframe[slot][items] = dframe.C.iloc[items]

我遇到了这个错误:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

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

此代码在 Python 2.7 中运行良好,但在 3.x 中运行不佳。我哪里出错了?

开始于

to_be_appended = pd.get_dummies(dframe.B).replace(0, np.nan).mul(dframe.C, axis=0)

然后连接

dframe = pd.concat([dframe, to_be_appended], axis=1)

看起来像:

print dframe

    A  B  C    a    b    c
10  a  a  1  1.0  NaN  NaN
11  b  a  2  2.0  NaN  NaN
12  c  b  3  NaN  3.0  NaN
13  d  b  4  NaN  4.0  NaN
14  e  c  5  NaN  NaN  5.0

搜索注意事项。

这是将一种热编码与广播乘法相结合。

Chained assignment will now by default warn if the user is assigning to a copy.

这可以通过选项 mode.chained_assignment 更改,允许的选项是 raise/warn/None。请参阅文档。

在[5]中:dfc = DataFrame({'A':['aaa','bbb','ccc'],'B':[1, 2,3]})

在 [6] 中:pd.set_option('chained_assignment','warn')

如果尝试这样做,将显示以下警告/异常。

在[7]中:dfc.loc[0]['A'] = 1111

回溯(最近调用最后) ... 设置复制警告: 试图在 DataFrame 的切片副本上设置一个值。 尝试使用 .loc[row_index,col_indexer] = value 代替 下面是正确的赋值方法。

在 [8] 中:dfc.loc[0,'A'] = 11

在[9]中:dfc

 A  B

0 11 1

1 bbb 2

2 ccc 3