簡體   English   中英

如何在 for 循環中按組計數的遞減順序訪問 pandas groupby 組?

[英]How to access pandas groupby groups in decreasing order of group count in a for loop?

我使用 pandas groupby 使用多列對我的數據進行分組。 現在,我想按組計數的遞減順序訪問 for 循環中的組?

groups.size().sort_values(ascending = False).head(10)以組計數的遞減順序向我顯示組,但我想在 for 循環中將每個組作為數據框(如 get_group() 返回)訪問? 我怎么做?

這就是小組的樣子

正如您的問題所暗示的,使用get_group

df = pd.DataFrame({'col': list('ABBCACBBC')})

# assign GroupBy object to variable
g = df.groupby('col', sort=False)

# get desired order of the groups
order = g['col'].size().sort_values(ascending=False).index

for x in order:
    print(f'# group {x}')
    print(g.get_group(x))

Output:

# group B
  col
1   B
2   B
6   B
7   B
# group C
  col
3   C
5   C
8   C
# group A
  col
0   A
4   A

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM