[英]Group by DataFrame based on consecutive ordered values
我正在嘗試根據值的順序對 dataframe 進行分組。 這是我的示例代碼:
import pandas as pd
df = pd.DataFrame([{'c1': 'v1', 'c2': 1},
{'c1': 'v1', 'c2': 2},
{'c1': 'v2', 'c2': 3},
{'c1': 'v1', 'c2': 4},
{'c1': 'v2', 'c2': 5},
{'c1': 'v2', 'c2': 6},
{'c1': 'v3', 'c2': 7}])
df['test'] = 'test'
df1 = df.groupby(['test', 'c1'])['c2'].describe()[['min', 'max']]
print(df1)
這是結果:
min max
test c1
test v1 1.0 4.0
v2 3.0 6.0
v3 7.0 7.0
但我正在尋找獲得以下結果的可能性:
min max
test c1
test v1 1.0 2.0
v2 3.0 3.0
v1 4.0 4.0
v2 5.0 6.0
v3 7.0 7.0
采用:
df1 = df.groupby(['test', 'c1', df.c1.ne(df.c1.shift()).cumsum()]).c2.describe()[['min', 'max']].droplevel(2)
結果:
min max
test c1
test v1 1.0 2.0
v1 4.0 4.0
v2 3.0 3.0
v2 5.0 6.0
v3 7.0 7.0
注意在轉換結束時使用pandas.MultiIndex.droplevel方法,它從 dataframe 多索引中刪除級別。
IIUC 你需要按連續的c1
分組:
df1 = (df.assign(group=df["c1"].ne(df["c1"].shift()).cumsum())
.groupby(['test', 'c1', "group"])['c2'].describe()[['min', 'max']]
.sort_index(level=2))
print(df1)
min max
test c1 group
test v1 1 1.0 2.0
v2 2 3.0 3.0
v1 3 4.0 4.0
v2 4 5.0 6.0
v3 5 7.0 7.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.