【问题标题】:Python Dataframe Create a rolling aggregate of list column with a windowPython Dataframe创建带有窗口的列表列的滚动聚合
【发布时间】:2021-08-26 14:53:48
【问题描述】:

我有一个包含一列列表的 df。

Python Pandas rolling aggregate a column of lists

import pandas as pd
import numpy as np
# Get some time series data
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
input_cols = ['A', 'B']
df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)

我想知道是否有办法为给定窗口创建“single_input_vector”列的滚动聚合。我查看了以下 SO 链接,但它没有提供包含窗口的方法。在我的情况下,窗口 3 的所需输出列将是:

Row1: [[24.68, 164.93]] 
Row2: [[24.68, 164.93], [24.18, 164.89]]
Row3: [[24.68, 164.93], [24.18, 164.89], [23.99, 164.63]] 
Row4: [[24.18, 164.89], [23.99, 164.63], [24.14, 163.92]]

等等。

【问题讨论】:

    标签: python list dataframe window rolling-computation


    【解决方案1】:

    我想不出更有效的方法来做到这一点,所以虽然这确实有效,但在海量数据集上可能存在性能限制。

    我们基本上是使用滚动计数来创建一组切片索引的开始:停止。

    import pandas as pd
    import numpy as np
    # Get some time series data
    df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
    input_cols = ['A', 'B']
    df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)
    
    
    window = 3
    
    df['len'] = df['A'].rolling(window=window).count()
    
    df['vector_list'] = df.apply(lambda x: df['single_input_vector'][max(0,x.name-(window-1)):int(x.name)+1].values, axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-06
      • 2020-08-14
      • 2018-08-21
      • 2019-03-16
      • 2020-07-01
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多