如何使用 Python Pandas 来计算向后跳过的行的平均值?

How to use Python Pandas to calculate the mean for skipped backward rows?

这是数据:

data = {'col1': [12, 13, 5, 2, 12, 12, 13, 23, 32, 65, 33, 52, 63, 12, 42, 65, 24, 53, 35]}
df = pd.DataFrame(data)

我想创建一个新列 skipped_mean。只有最后 3 行具有此变量的有效值。它的作用是向后看6行,连续3次,取三个数的平均值

如何做到?

您可以使用加权滚动平均法来做到这一点:

import numpy as np

weights = np.array([1/3,0,0,0,0,0,1/3,0,0,0,0,0,1/3])
df['skipped_mean'] = df['col1'].rolling(13).apply(lambda x: np.sum(weights*x))