在DataFrame的切片副本上设置值 [英] Setting values on a copy of a slice from a DataFrame
问题描述
我有一个小的数据框,说一个:
I have a small dataframe, say this one :
Mass32 Mass44
12 0.576703 0.496159
13 0.576658 0.495832
14 0.576703 0.495398
15 0.576587 0.494786
16 0.576616 0.494473
...
我希望列Mass32
的滚动平均值,所以我这样做:
I would like to have a rolling mean of column Mass32
, so I do this:
x['Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
它的工作原理与我有一个名为Mass32s
的新列一样,其中包含了我希望包含的内容,但我也收到警告消息:
It works as in I have a new column named Mass32s
which contains what I expect it to contain but I also get the warning message:
试图在DataFrame的切片副本上设置一个值.尝试 改用.loc [row_indexer,col_indexer] =值
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
请参阅文档中的注意事项: http://pandas.pydata.org/pandas -docs/stable/indexing.html#indexing-view-versus-copy
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
我想知道是否有更好的方法,特别是避免收到此警告消息.
I'm wondering if there's a better way to do it, notably to avoid getting this warning message.
推荐答案
出现此警告是因为数据框x
是切片的副本.这不容易知道为什么,但是与您如何达到当前状态有关.
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
您可以通过x在x中创建合适的dataframe
You can either create a proper dataframe
out of x by doing
x = x.copy()
这将删除警告,但这是不正确的方式
This will remove the warning, but it is not the proper way
如警告所示,您应该使用DataFrame.loc
方法,如下所示:
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
这篇关于在DataFrame的切片副本上设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!