设置带有复制警告的 pandas [英] Pandas SettingWithCopyWarning

查看:32
本文介绍了设置带有复制警告的 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.4和Pandas 0.15.0

Python 3.4 and Pandas 0.15.0

df是一个数据框,而col1是一列.在下面的代码中,我正在检查值10的存在并将其替换为1000.

df is a dataframe and col1 is a column. With the code below, I'm checking for the presence of the value 10 and replacing such values with 1000.

df.col1[df.col1 == 10] = 1000

这是另一个例子.这次,我要根据索引更改col2中的值.

Here's another example. This time, I'm changing values in col2 based on index.

df.col2[df.index == 151] = 500

这两种情况都会产生以下警告:

Both these produce the warning below:

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

这会产生类似的警告,并带有建议:

This produces a similar warning, with an added suggestion:

Try using .loc[row_indexer,col_indexer] = value instead

我不确定我是否理解警告中指出的讨论.编写这三行代码的更好的方法是什么?

I'm not sure I understand the discussion pointed to in the warnings. What would be a better way to write these three lines of code?

请注意,该操作有效.

推荐答案

此处的问题是:df.col1[df.col1 == 10]返回一个副本.

The issue here is that: df.col1[df.col1 == 10] returns a copy.

所以我会说:

row_index = df.col1 == 10
# then with the form .loc[row_indexer,col_indexer]
df.loc[row_index, 'col1'] = 100

这篇关于设置带有复制警告的 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆