[英]Pandas rolling mean with variable window based on an different column
I would like to perform the rolling mean on a window that varies depending on the values of a column in my DataFrame.我想在一个窗口上执行滚动平均值,该窗口根据我的 DataFrame 中列的值而变化。 Can anyone help me?谁能帮我? Here is a starting point:这是一个起点:
import pandas as pd
import numpy as np
rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 2)), columns=list('AB'))
df.loc[:,'B']=df['B']//10
Now I would like to get the rolling mean of the series df.A
with the window based on column B. For example if df.B[0]
is worth 3 my_series[0]=df.A.rolling(3).mean()[0]
and so on for my_series[1]
etc...现在我想通过基于 B 列的窗口获得df.A
系列的滚动平均值。例如,如果df.B[0]
值 3 my_series[0]=df.A.rolling(3).mean()[0]
等等my_series[1]
等等...
Can you help me?你能帮助我吗? ty for your time I appreciate it.我很感激你的时间。
One option is to loop through the data frame, and assign a new column equal to the rolling_mean for each row.一种选择是循环遍历数据框,并为每一行分配一个等于rolling_mean 的新列。
df['rolling_mean'] = np.nan
for ind in range(len(df)):
df.loc[df.index[ind], 'rolling_mean'] = df.A.rolling(df.loc[df.index[ind], 'B']).mean()[ind]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.