簡體   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