我有一個 DataFrame,我想將它分成多個組。每個組將是一系列行,其中列difference等于 1。如果不是,則跳過它并找到下一行difference等于 1 并開始一個新組。
例如這個:
id difference
0 001 1
1 001 1
2 001 1
3 001 1
4 001 1
5 001 1
6 001 2
7 001 2
8 001 1
9 001 1
10 001 1
11 001 1
12 001 4
13 001 1
14 001 1
15 001 1
16 001 1
17 001 1
18 001 1
19 001 1
將是 3 dfs 第一個:從 0 到 5(包括 5),第二個:從 8 到 11,第三個:從 13 到 19
現在我是這樣做的,而且我是熊貓的新手。有沒有其他有效的方法來做到這一點?
grouped = g.df((g['difference'] != g['difference'].shift()).cumsum())
for group_id, group in grouped:
if (group['difference'].iloc[0] < 1.1) & (group['difference'].iloc[0] > 0.9) and len(
group.index) > 1:
#do stuff...
uj5u.com熱心網友回復:
給定您的 splitting condition,用于cumsum為 . 創建偽組groupby。然后用于loc忽略違反的行condition并在字典理解中提取組:
condition = df.difference != 1
dfs = {key: data for key, data in df.loc[~condition].groupby(condition.cumsum())}
請注意,如果您想包含id作為拆分條件,只需將其添加到groupby并相應地解壓縮:
dfs = {key: data for (_, key), data in df.loc[~condition].groupby(['id', condition.cumsum()])}
# ^^^^^^^^ ^^^^
輸出:
{0:
id difference
0 001 1
1 001 1
2 001 1
3 001 1
4 001 1
5 001 1,
2:
id difference
8 001 1
9 001 1
10 001 1
11 001 1,
3:
id difference
13 001 1
14 001 1
15 001 1
16 001 1
17 001 1
18 001 1
19 001 1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369015.html
標籤:Python 熊猫 数据框 pandas-groupby
下一篇:創建資料框串列的資料框
