繁体   English   中英

Groupby连续值和聚合

[英]Groupby consecutive values and aggregate

这是我的数据集(pandas DataFrame df ):

DateTime              INDICATOR
2017-01-01 10:35:00   0
2017-01-01 10:40:00   0
2017-01-01 10:45:00   0
2017-01-01 10:50:00   0
2017-01-01 10:55:00   0
2017-01-01 11:00:00   0
2017-01-01 11:05:00   1
2017-01-01 11:10:00   1
2017-01-01 11:15:00   1
2017-01-01 11:20:00   1
2017-01-01 11:25:00   0
2017-01-01 11:30:00   0
2017-01-01 11:35:00   1
2017-01-01 11:40:00   1
2017-01-01 11:45:00   1

DateTime列的类型为datetime64[ns]

我想获得INDICATOR等于1的数据段的持续时间(以分钟为单位)。

预期的结果是:

[15, 10]

这是我尝试解决此任务的方式,但我收到所有0值:

s=df["INDICATOR"].eq(1)
df1=df[s].copy()
s1=df1.groupby(s.cumsum())["DateTime"].transform(lambda x : x.max()-x.min()).dt.seconds

s1所有值都是0。

首先,使用以下方法创建groupID:

gb_ID = df.INDICATOR.diff().ne(0).cumsum()

接下来,只选择INDICATOR == 1并通过gb_ID进行groupby 查找每个gb_ID的DateTime maxmin 找到这个maxmin diff 最后,选择列而不是NaT将其转换为分钟的int并调用values以返回数组。

df.query('INDICATOR == 1').groupby(gb_ID)['DateTime'].agg(['min', 'max']) \
                          .diff(axis=1)['max'].dt.seconds.floordiv(60).values

Out[351]: array([15, 10], dtype=int64)

下面是选择非NaTvalues之前的数据帧

df.query('INDICATOR == 1').groupby(gb_ID)['DateTime'].agg(['min', 'max']).diff(axis=1)

Out[362]:
          min      max
INDICATOR
2         NaT 00:15:00
4         NaT 00:10:00

考虑到这篇文章,我想用np.split()将数据帧分成子帧。

尝试这个:

from numpy import nan

# split df on condition that indicator is 0
splitted_dfs = np.split(df, *np.where(df. INDICATOR == 0))

results = []

for split in splitted_dfs:
    # iloc[1:] omits the first 0 entry of the splitted df
    results.append(split.iloc[1:].index.max() - split.iloc[1:].index.min())

print([int(x.seconds / 60) for x in results if x.seconds is not nan])

# prints to [15, 10]

说明

具有条件INDICATOR == 0 np.split()在满足条件的每一行上进行拆分。 这产生了这个数据帧列表:

2017-01-01 10:35:00          0, INDICATOR

2017-01-01 10:40:00          0, INDICATOR

2017-01-01 10:45:00          0, INDICATOR

2017-01-01 10:50:00          0, INDICATOR

2017-01-01 10:55:00          0, INDICATOR

2017-01-01 11:00:00          0
2017-01-01 11:05:00          1
2017-01-01 11:10:00          1
2017-01-01 11:15:00          1
2017-01-01 11:20:00          1, INDICATOR

2017-01-01 11:25:00          0, INDICATOR

2017-01-01 11:30:00          0
2017-01-01 11:35:00          1
2017-01-01 11:40:00          1
2017-01-01 11:45:00          1

您可以迭代该列表,忽略空列表并删除相关列表的前0个条目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM