【发布时间】:2020-06-13 12:05:33
【问题描述】:
也许 pandas.DataFrame.rolling 不是最好的方法,请告诉我是否有更好的方法。
我想要的是在 df 上有滚动窗口,并让 df 中的所有列在窗口中可用以进行各种计算。
我相信下面的代码非常接近我的目标,但我很难理解代码中所述的索引问题。
首先x.index = RangeIndex(start=0, stop=2, step=1),tmp_df正确选择了df中的第一行和第二行(索引0和1)。对于最后一个 x.index = RangeIndex(start=4, stop=6, step=1) 似乎 iloc 尝试在 df 中选择超出范围的索引 6(df 的索引为 0 到 5)。
我错过了什么?
提前感谢您的任何建议。
import numpy as np
import pandas as pd
df = pd.DataFrame({'open': [7, 5, 10, 11,6,12],
'close': [6, 6, 11, 10,7,10],
'positive': [0, 1, 1, 0,1,0]},
)
def do_calculations_on_any_df_column_in_window(x,df):
print("index:",x.index)
tmp_df = df.iloc[x.index] # raises "ValueError: cannot set using a slice indexer with a different length than the value" when x.index = RangeIndex(start=4, stop=6, step=1) as df index goes from 0 to 5 only
# do calulations on any column in tmp_df, get result
result = 1 #dummyresult
return result
intervals = range(2, 10)
for i in intervals:
df['result_' + str(i)] = np.nan
res = df.rolling(i).apply(do_calculations_on_any_df_column_in_window, args=(df,), raw=False)
df['result_' + str(i)][1:] = res
print(df)
【问题讨论】:
标签: python pandas slice valueerror rolling-computation