[英]SettingWithCopyWarning after using Pandas Dataframe filter function
The objective of my code is to overwrite a dataframe with a filtered version. 我的代码的目的是使用过滤后的版本覆盖数据框。 The following code returns the warning beneath: 以下代码返回以下警告:
code: 码:
df = df[df.col>1]
df.col2 = df.col2.astype(float)
error: 错误:
/root/.virtualenvs/data_tools/local/lib/python2.7/site-packages/pandas/core/generic.py:2177: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
theory: 理论:
The error occurs on the second line but only happens if the first line is run previously. 该错误发生在第二行,但仅在第一行先前运行时才会发生。 I believe that the first line is creating a copy of df with the same name as the original which then causes the error. 我相信第一行正在创建与原始名称相同的df副本,然后导致错误。 I cannot work out why though. 我不知道为什么。
module versions: 模块版本:
numpy==1.10.1 numpy的== 1.10.1
pandas==0.16.2 大熊猫== 0.16.2
The issue as Jeff pointed out is that I was making a view not a copy of the dataframe. Jeff指出的问题是,我正在制作视图,而不是复制数据框。
This is what I should have written: 这是我应该写的:
df = df[df.col>1].copy(deep=True) df = df [df.col> 1] .copy(deep = True)
df.col2 = df.col2.astype(float) df.col2 = df.col2.astype(float)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.