为什么我会尝试从DataFrame警告中对切片的副本进行设置

时间:2018-11-27 09:47:48

标签: pandas

运行以下代码时:

import pandas as pd
df = pd.DataFrame({"A": [1,2,3],"B": [2,4,8]})
df2 = df[df["A"] < 3]
df2["C"] = 100

我收到以下警告:

  

SettingWithCopyWarning:一个值   试图在DataFrame的切片副本上进行设置。尝试使用   .loc [row_indexer,col_indexer] = value相反,请参见   说明文件:   http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

但这正是我想要的行为(实际表很大,我不想复制它),为什么会收到警告?为什么有风险?

df

   A  B
0  1  2
1  2  4
2  3  8

df2

   A  B    C
0  1  2  100
1  2  4  100

1 个答案:

答案 0 :(得分:1)

为什么会这样?

因为df2df的一部分的副本。

为什么有风险?

这是一条消息,告诉您df2df是不同的东西。之所以引入它,是因为并非总是如此。

从文档中获取示例代码:

def do_something(df):
   foo = df[['bar', 'baz']]  # Is foo a view? A copy? Nobody knows!
   # ... many lines here ...
   foo['quux'] = value       # We don't know whether this will modify df or not!
   return foo

我该如何解决?

通过显式复制切片:

df2 = df[df['A'] < 3].copy()
df2['C'] = 100

或使用loc

df.loc[df['A'] < 3, 'C'] = 100