我创建了一个Pandas数据帧df
:
df.head()
Out[1]:
A B DateTime
2010-01-01 50.662365 101.035099 2010-01-01
2010-01-02 47.652424 99.274288 2010-01-02
2010-01-03 51.387459 99.747135 2010-01-03
2010-01-04 52.344788 99.621896 2010-01-04
2010-01-05 47.106364 98.286224 2010-01-05
我可以添加A列的移动平均值:
df['A_moving_average'] = df.A.rolling(window=50, axis="rows")
.apply(lambda x: np.mean(x))
问题:如何添加列A和B的移动平均值?
这应该可以工作,但出现错误:
df['A_B_moving_average'] = df.rolling(window=50, axis="rows")
.apply(lambda row: (np.mean(row.A) + np.mean(row.B)) / 2)
错误为:
NotImplementedError: ops for Rolling for this dtype datetime64[ns] are not implemented
下面是我如何创建测试 pandas 数据帧df
:
import numpy.random as rnd
import pandas as pd
import numpy as np
count = 1000
dates = pd.date_range('1/1/2010', periods=count, freq='D')
df = pd.DataFrame(
{
'DateTime': dates,
'A': rnd.normal(50, 2, count), # Mean 50, standard deviation 2
'B': rnd.normal(100, 4, count) # Mean 100, standard deviation 4
}, index=dates
)
我找不到直接解决rolling
中使用多列的一般问题的方法-但在您的特定情况下,您可以只取A列和B列的平均值,然后应用rolling
:
df['A_B_moving_average'] = ((df.A + df.B) / 2).rolling(window=50, axis='rows').mean()
axis='rows'
为rolling
指定整个DataFrame,则每列都是单独执行的。因此:
df['A_B_moving_average'] = df.rolling(window=5, axis='rows').mean()
将首先评估A
(Works)的滚动窗口,然后评估B
(Works)的滚动窗口,然后评估DateTime
的滚动窗口(不工作,因此出现错误)。每个滚动窗口都是一个普通的NumPy数组,因此您无法访问"列名"。就像使用print
s:
import numpy.random as rnd
import pandas as pd
import numpy as np
count = 10
dates = pd.date_range('1/1/2010', periods=count, freq='D')
df = pd.DataFrame(
{
'DateTime': dates,
'A': rnd.normal(50, 2, count), # Mean 50, standard deviation 2
'B': rnd.normal(100, 4, count) # Mean 100, standard deviation 4
}, index=dates
)
df[['A', 'B']].rolling(window=6, axis='rows').apply(lambda row: print(row) or np.max(row))
打印:
[ 47.32327354 48.12322447 50.86806381 49.3676319 47.81335338
49.66915104]
[ 48.12322447 50.86806381 49.3676319 47.81335338 49.66915104
48.01520798]
[ 50.86806381 49.3676319 47.81335338 49.66915104 48.01520798
48.14089864]
[ 49.3676319 47.81335338 49.66915104 48.01520798 48.14089864
51.89999973]
[ 47.81335338 49.66915104 48.01520798 48.14089864 51.89999973
48.76838054]
[ 100.10662696 96.72411985 103.24600664 95.03841539 95.23430836
102.30955102]
[ 96.72411985 103.24600664 95.03841539 95.23430836 102.30955102
95.18273088]
[ 103.24600664 95.03841539 95.23430836 102.30955102 95.18273088
97.36751546]
[ 95.03841539 95.23430836 102.30955102 95.18273088 97.36751546
99.25325622]
[ 95.23430836 102.30955102 95.18273088 97.36751546 99.25325622
105.16747544]
第一个来自A
列,最后一个来自B
列,均为纯数组。
这篇关于如何对 pandas 数据帧的每一行使用.roll()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!