Pandas中的移动平均值

3

我有一个包含3列的csv文件,想要计算其中1列的移动平均值。我想要创建一个新的列来保存移动平均值。

import pandas as pd

df= pd.read_csv('csv',usecols=['speed','col2', 'col3'])
df['MA'] = df.rolling( window=5, on='speed').mean
print(df)

它不再显示任何列。只有索引和...。

1   ...
2   ...
3   ...
3   ...
4   ...

[4 rows x 4 columns]

如果我更改为:

df= df.rolling(window=5, on='speed').mean
print(df)

它只返回给我这个:
<bound method Rolling.mean of Rolling [window=5,center=False,axis=0,on=speed]>

Process finished with exit code 0

2
遗漏了(),像这样df['MA'] = df.rolling(window=5, on='speed').mean() - jezrael
我现在遇到一个错误:ValueError: Wrong number of items passed 2, placement implies 1。 - Michelle
这取决于使用的列。如果我将 usecols 更改为“speed”,那么它就可以正常工作。 - Michelle
1个回答

6
发布另一种方式。
     df['MA'] = df['speed'].rolling(window=5).mean()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接