For*_*892 15 python pandas pandas-groupby
我有以下熊猫数据框:
data = {
'ID': [100, 100, 100, 100, 200, 200, 200, 200, 200, 300, 300, 300, 300, 300],
'value': [False, False, True, False, False, True, True, True, False, False, False, True, True, False],
}
df = pandas.DataFrame (data, columns = ['ID','value'])
Run Code Online (Sandbox Code Playgroud)
我想获得以下组:
这可以用熊猫来完成吗?
我试过了
group = df.groupby((df['value'].shift() != df['value']).cumsum())
Run Code Online (Sandbox Code Playgroud)
但这会返回错误的结果。
让我们尝试shift+cumsum创建 groupby 键:顺便说一句,我真的很喜欢您显示预期输出的方式
s = df.groupby('ID')['value'].apply(lambda x : x.ne(x.shift()).cumsum())
d = {x : y for x ,y in df.groupby(s)}
d[2]
ID value
2 100 True
5 200 True
6 200 True
7 200 True
11 300 True
12 300 True
d[1]
ID value
0 100 False
1 100 False
4 200 False
9 300 False
10 300 False
d[3]
ID value
3 100 False
8 200 False
13 300 False
Run Code Online (Sandbox Code Playgroud)