【问题标题】:Pandas dataframe, do calulations on any column in rolling window熊猫数据框,对滚动窗口中的任何列进行计算
【发布时间】: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


    【解决方案1】:

    试试这个功能:

    def calculate_on_rolling_window(df, win, col_names):
        #final_df = pd.DataFrame() # stores the complete results
        # calculate sd and mean for each tag
        for i in range(len(col_names)):
          current_column = col_names[i]
          df[current_column + '_mean_' +str(win)] = (df[current_column].rolling(window=win).mean())
          df[current_column + '_min_' +str(win)] = (df[current_column].rolling(window=win).min())
          df[current_column + '_max_' +str(win)] = (df[current_column].rolling(window=win).max())
        df = df.fillna(0)
        return(df)
    

    你得到这个结果

    col_names = df.columns
    df_extended = calculate_on_rolling_window(df,2,col_names)
    df_extended.head()
    
    open    close   positive    open_mean_2     open_min_2  open_max_2  close_mean_2    close_min_2     close_max_2     positive_mean_2     positive_min_2  positive_max_2
    0     7       6       0           0.0              0.0          0.0        0.0             0.0            0.0             0.0                   0.0           0.0
    1     5       6       1           6.0              5.0          7.0        6.0             6.0            6.0             0.5                   0.0           1.0
    2     10      11      1           7.5              5.0          10.0       8.5             6.0            11.0            1.0                   1.0           1.0
    3     11      10      0           10.5             10.0         11.0       10.5            10.0           11.0            0.5                   0.0           1.0
    4     6       7       1           8.5              6.0          11.0       8.5             7.0            10.0            0.5                   0.0           1.0
    

    【讨论】:

    • 谢谢 BICube :) 你知道我将如何在窗口上进行自定义计算吗?例如,有一个正值为 0,1,1,0,1 的窗口我希望结果为 2,因为连续有两个正值。如果窗口包含 1,1,1,1,0,我希望结果为 4(连续正数的总和)
    • 请看我编辑的评论,你能帮忙吗?一旦我了解如何进行上述自定义计算,我将支持/标记接受答案。
    • @Urdar 这是一个单独的问题,我在您的原始问题中看不到明确提及。可以考虑在 SO 上提出一个新问题,即关于有一个自定义函数来对序列中的连续数字求和。
    猜你喜欢
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2018-09-02
    • 2020-11-14
    • 2023-01-25
    • 2017-03-30
    相关资源
    最近更新 更多