如何获取 groupby 中的第一个值,类型错误:first() 缺少 1 个必需的位置参数:'offset'

Vic*_*cky 5 python group-by dataframe pandas

我有 df,像这样

States Counts
AK     one
AK     two
AK     one
LO     one
LO     three
LO     three
Run Code Online (Sandbox Code Playgroud)

尝试获取每种状态出现次数最多的计数

我的代码:

 df.groupby('States')['Counts'].value_counts().first(), gives 
Run Code Online (Sandbox Code Playgroud)

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

预期输出:

  States Counts
  AK     one
  LO     three
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

使用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
Run Code Online (Sandbox Code Playgroud)

  • `df.groupby('States')['Counts'].apply(lambda x : x.mode())` (4认同)