[英]Grouping pandas dataframe by blocks using identical values
I have a big dataframe which is structured as follows:我有一个大的 dataframe,其结构如下:
|'Type'| |'类型'| |'col2'| |'col2'| |'col3'| |'col3'|
| | ----- | ----- | | | -----| -----| |-----| |-----|
'A' '一个'
'B' '乙'
'C' 'C'
'C' 'C'
'C' 'C'
'B' '乙'
C C
C C
C C
A一个
B乙
C C
C C
B乙
C C
A一个
So the types are like hierarchies;所以类型就像层次结构; As with one or multiple Bs, which have one or multiple Cs.与具有一个或多个 C 的一个或多个 B 一样。 I would like to split up this dataframe into 2 different kinds of chunks:我想把这个 dataframe 分成两种不同的块:
How can I do this?我怎样才能做到这一点?
IIUC, you want col2 to have groups starting with A and col3 subgroups starting with B: IIUC,您希望 col2 具有以 A 开头的组和以 B 开头的 col3 子组:
df['col2'] = df['Type'].eq('A').cumsum()
df['col3'] = df['Type'].eq('B').groupby(df['col2']).cumsum()
output: output:
Type col2 col3
0 A 1 0
1 B 1 1
2 C 1 1
3 C 1 1
4 C 1 1
5 B 1 2
6 C 1 2
7 C 1 2
8 C 1 2
9 A 2 0
10 B 2 1
11 C 2 1
12 C 2 1
13 B 2 2
14 C 2 2
15 A 3 0
You can then use col2/col3 to groupby
:然后,您可以使用 col2/col3 到groupby
:
m = df[['col2', 'col3']].ne(0).all(1)
for name, g in df[m].groupby(['col2', 'col3']):
print(f'group {name}')
print(g)
output: output:
group (1, 1)
Type col2 col3
1 B 1 1
2 C 1 1
3 C 1 1
4 C 1 1
group (1, 2)
Type col2 col3
5 B 1 2
6 C 1 2
7 C 1 2
8 C 1 2
group (2, 1)
Type col2 col3
10 B 2 1
11 C 2 1
12 C 2 1
group (2, 2)
Type col2 col3
13 B 2 2
14 C 2 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.