【问题标题】:Pandas: return the occurrences of the most frequent value for each group (possibly without apply)Pandas:返回每组出现频率最高的值(可能没有应用)
【发布时间】:2021-02-12 05:07:19
【问题描述】:

假设输入数据集:

test1 = [[0,7,50], [0,3,51], [0,3,45], [1,5,50],[1,0,50],[2,6,50]]
df_test = pd.DataFrame(test1, columns=['A','B','C'])

对应于:

    A   B   C
0   0   7   50
1   0   3   51
2   0   3   45
3   1   5   50
4   1   0   50
5   2   6   50

我想获取按“A”分组的数据集,以及每个组中“B”最常见的值,以及该值的出现次数:

A   most_freq freq
0   3          2
1   5          1
2   6          1

我可以通过以下方式获得前 2 列:

grouped = df_test.groupby("A")
out_df = pd.DataFrame(index=grouped.groups.keys())
out_df['most_freq'] = df_test.groupby('A')['B'].apply(lambda x: x.value_counts().idxmax())

但我在最后一列遇到问题。 另外:有没有更快的方法不涉及“应用”?这个解决方案不能很好地适应更大的输入(我也尝试过 dask)。

非常感谢!

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    使用默认排序的SeriesGroupBy.value_counts,因此在Series.reset_index之后添加DataFrame.drop_duplicates作为最高值:

    df = (df_test.groupby('A')['B']
                 .value_counts()
                 .rename_axis(['A','most_freq'])
                 .reset_index(name='freq')
                 .drop_duplicates('A'))
    print (df)
       A  most_freq  freq
    0  0          3     2
    2  1          0     1
    4  2          6     1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-01
      • 2018-03-24
      • 2022-06-10
      • 2019-08-15
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多