Pandas 设置副本警告
这是关于Python 3.4和Pandas 0.15.0的内容。
这里的df是一个数据框,而col1是其中的一列。下面的代码是用来检查值10是否存在,并把这些值替换成1000。
df.col1[df.col1 == 10] = 1000
这是另一个例子。这次,我是根据索引来改变col2中的值。
df.col2[df.index == 151] = 500
这两段代码都会产生下面的警告:
-c:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
最后,
cols = ['col1', 'col2', 'col3']
df[cols] = df[cols].applymap(some_function)
这段代码也会产生类似的警告,并附带一个建议:
Try using .loc[row_indexer,col_indexer] = value instead
我不太明白警告中提到的讨论。有没有更好的方法来写这三行代码呢?
需要注意的是,这些操作是有效的。
2 个回答
5
我同意保罗关于'loc'用法的看法。
对于你的applymap情况,你应该可以这样做:
cols = ['col1', 'col2', 'col3']
df.loc[:, cols] = df[cols].applymap(some_function)
39
这里的问题是:df.col1[df.col1 == 10]
返回的是一个副本。
所以我想说:
row_index = df.col1 == 10
# then with the form .loc[row_indexer,col_indexer]
df.loc[row_index, 'col1'] = 100