如何根据groupby数据帧的值计数筛选它们

2024-09-28 05:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个groupby数据帧,我想返回具有最高值计数的前3个组

例如,下面的数据帧预期输出表应该是group20,30和33

我想显示一个原始数据集表,但是组函数没有正确显示,所以我上传了一个图像

                     amount         cosine_group
cosine_group            

0                   952.5              0
4                   3000.0             4    
20                  2000.0            20
                    2000.0            20
                    2000.0            20
27                  2000.0            27    

30                  2100.0            30
                    2100.0            30
                    2100.0            30
33                  1065.0            33
                    1065.0            33
                    1065.0            33
                    1065.0            33

预期产出:

                     amount         cosine_group
cosine_group            

20                  2000.0            20
                    2000.0            20
                    2000.0            20

30                  2100.0            30
                    2100.0            30
                    2100.0            30
33                  1065.0            33
                    1065.0            33
                    1065.0            33
                    1065.0            33

enter image description here


Tags: 数据函数图像原始数据groupamount计数groupby
2条回答

这可能不太像Python,但肯定能完成工作

# retieve the index of the value counts
cosine_group_value = df["cosine_group"].value_counts().index

# get the fist 3 values  from the value counts (highest 3 values)
top3 = list(cosine_group_value)[:3]

# filter your dataframe using the top 3 values on the cosine_group column
df = df[df["cosine_group"].isin(top3)]

您可以使用^{}选择3个最大的尺寸。使用.isin()匹配具有这些值的行。最后,使用.loc返回原始数据帧中最大元素的行,如下所示:

df = df.rename_axis(index='cosine_group0')   # to rename index axis name
df.loc[df['cosine_group'].isin(df.groupby('cosine_group', as_index=False)['cosine_group'].size().nlargest(3, 'size')['cosine_group'].tolist())]

或使用:

df = df.rename_axis(index='cosine_group0')   # to rename index axis
df.loc[df["cosine_group"].isin(df["cosine_group"].value_counts().nlargest(3).index)]

相关问题 更多 >

    热门问题