首页 > 解决方案 > 当满足时间序列的条件时,Python Pandas 会聚合过去的行

问题描述

我有一个时间序列问题,我想根据某个列中出现的值聚合一些数据。为了说明,请考虑下表

日期 可乐 colB 科尔C
2019-01-01 1 -10 无效的
2019-01-02 2 -5 无效的
2019-01-03 3 0 101
2019-01-04 4 5 101
2019-01-05 5 10 101
2019-01-06 6 15 无效的
2019-01-07 7 20 101

我想完成以下任务:

  1. 当 colC 的值不为空时,将值聚合到该行并获取日期列的增量
  2. 如果 colC 的元素 X 不为空,但元素 (X-1) 也不为空,则忽略行 X。

对于上一个表,结果将是

聚合(colC) 平均(colA) 平均(colB) delta(日期)[以天为单位]
101 2 -5 2
101 6.5 17.5 1

到目前为止,我找不到任何方法来实现这一点

标签: pythonpandas

解决方案


尝试groupby

#convert Date column to datetime if needed
df["Date"] = pd.to_datetime(df["Date"])

#keep only rows where there aren't consecutive non-null values
df2 = df[~(df["colC"].notnull()&df["colC"].shift().notnull())]

#groupby consecutive null values and aggregate
output = df2.groupby(df2["colC"].notnull().shift().cumsum().fillna(0)) \
            .agg({"colA": "mean", \
                  "colB": "mean", \
                  "colC": "first", \
                  "Date": lambda x: (x.max()-x.min()).days}) \
            .rename_axis(None) \
            .rename(columns={"Date": "Delta"})

>>> output
     colA  colB   colC  Delta
0.0   2.0  -5.0  101.0      2
1.0   6.5  17.5  101.0      1

推荐阅读