【问题标题】:Group by a column to find the most frequent value in another column? [duplicate]按列分组以查找另一列中出现频率最高的值? [复制]
【发布时间】:2023-03-04 15:58:01
【问题描述】:

按列分组以在另一列中查找最常见的值。 示例:

import pandas as pd
d = {'col1': ['green','green','green','blue','blue','blue'],'col2': ['gx','gx','ow','nb','nb','mj']}
df = pd.DataFrame(data=d)
df

给予:

col1   col2
green  gx
green  gx
green  ow
blue   nb
blue   nb
blue   xv

结果:

green 拥有gxblue 拥有nb

【问题讨论】:

  • 我可能不够清楚,但我不想要这个。我只想保留具有最频繁值的行。
  • 对不起,我后来意识到了:(

标签: python pandas group-by pandas-groupby


【解决方案1】:

使用SeriesGroupBy.value_counts 并选择索引的第一个值:

df = df.groupby('col1')['col2'].apply(lambda x: x.value_counts().index[0]).reset_index()
print (df)
    col1 col2
0   blue   nb
1  green   gx

或添加DataFrame.drop_duplicates:

df = df.groupby('col1')['col2'].value_counts().reset_index(name='v')

df = df.drop_duplicates('col1')[['col1','col2']]
print (df)
    col1 col2
0   blue   nb
2  green   gx

或使用Series.mode 并按Series.iat 的位置选择第一个值:

df = df.groupby('col1')['col2'].apply(lambda x: x.mode().iat[0]).reset_index()
print (df)
    col1 col2
0   blue   nb
1  green   gx

编辑:

问题仅在于 NaNs 组:

d = {'col1': ['green','green','green','blue','blue','blue'],
     'col2': [np.nan,np.nan,np.nan,'nb','nb','mj']}
df = pd.DataFrame(data=d)

f = lambda x: np.nan if x.isnull().all() else x.value_counts().index[0]
#or
#f = lambda x: next(iter(x.value_counts().index), np.nan)
#another solution
#f = lambda x: next(iter(x.mode()), np.nan)
df = df.groupby('col1')['col2'].apply(f).reset_index()
print (df)
    col1 col2
0   blue   nb
1  green  NaN

【讨论】:

  • 我尝试将其应用于示例以外的数据框,它显示:IndexError: index 0 is out of bounds for axis 0 with size 0。你知道为什么吗?
  • @user10288621 - 当然,等一下。
  • @user10288621 - 检查已编辑的答案。
【解决方案2】:

您可以使用GroupBy + transformpd.Series.mode,然后是drop_duplicates

使用此解决方案,您的原始数据帧的索引得以保留。它假定只有一种模式,因此每组过滤一种模式。

modes = df.groupby('col1')['col2'].transform(lambda x: x.mode().iat[0])
res = df[df['col2'] == modes].drop_duplicates()

print(res)

    col1 col2
0  green   gx
3   blue   nb

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2019-04-03
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2017-07-18
    • 2011-09-09
    相关资源
    最近更新 更多