[英]Pandas group the rows in a dataframe based on specific column value
I have the data frame as like below one, 我的数据框如下图所示,
Input DataFrame
gw_mac mac
0 ac233fc015f6 dce83f3bc820
1 ac233fc015f6 ac233f264a4c
2 ac233fc015f6 ac233f264a4c
3 ac233fc015f6 dce83f3bc820
4 ac233fc015f6 ac233f264a4c
5 ac233fc015f6 ac233f264a4c
6 ac233fc015f6 dce83f3bc820
7 ac233fc015f6 e464eecba5eb
Now I need to group the dataframe based on the column values "gw_mac" and "mac" and I should get the following three different groups 现在,我需要根据列值“ gw_mac”和“ mac”对数据框进行分组,我应该得到以下三个不同的组
Expected Output
Group1
gw_mac mac
0 ac233fc015f6 dce83f3bc820
3 ac233fc015f6 dce83f3bc820
6 ac233fc015f6 dce83f3bc820
Group2
gw_mac mac
1 ac233fc015f6 ac233f264a4c
2 ac233fc015f6 ac233f264a4c
4 ac233fc015f6 ac233f264a4c
5 ac233fc015f6 ac233f264a4c
Group3
gw_mac mac
7 ac233fc015f6 e464eecba5eb
If need different groups by columns loop by groupby
object: 如果需要不同的组按列循环由
groupby
对象:
for i, g in df.groupby(['gw_mac','mac']):
print (g)
gw_mac mac
1 ac233fc015f6 ac233f264a4c
2 ac233fc015f6 ac233f264a4c
4 ac233fc015f6 ac233f264a4c
5 ac233fc015f6 ac233f264a4c
gw_mac mac
0 ac233fc015f6 dce83f3bc820
3 ac233fc015f6 dce83f3bc820
6 ac233fc015f6 dce83f3bc820
gw_mac mac
7 ac233fc015f6 e464eecba5eb
You can try this to create a dictionary of data frames with unique groups, 您可以尝试创建包含唯一组的数据框字典,
df['Group'] = df.groupby(['gw_mac', 'mac']).cumcount()
dfs = dict(tuple(df.groupby('Group')))
You can access a group using, 您可以使用
dfs[0]
gw_mac mac Group
0 ac233fc015f6 dce83f3bc820 0
1 ac233fc015f6 ac233f264a4c 0
7 ac233fc015f6 e464eecba5eb 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.