如何在groupby中获取第一个值,TypeError:first()缺少1个必需的位置参数:'offset'[duplicate]

问题描述 投票:3回答:1

这个问题在这里已有答案:

我有df,就像这样

States Counts
AK     one
AK     two
AK     one
LO     one
LO     three
LO     three

试图获得每个状态的最多计数

我的代码:

 df.groupby('States')['Counts'].value_counts().first(), gives 

TypeError: first() missing 1 required positional argument: 'offset'

预期产量:

  States Counts
  AK     one
  LO     three
python pandas dataframe group-by
1个回答
3
投票

使用lambda函数:

df = df.groupby('States')['Counts'].apply(lambda x: x.value_counts().index[0]).reset_index(name='val')
print (df)
  States    val
0     AK    one
1     LO  three
© www.soinside.com 2019 - 2024. All rights reserved.