【发布时间】:2021-11-13 02:46:28
【问题描述】:
我有一个包含两列的数据框。我需要按其中一列分组,然后找到具有最大行数的组和该组的名称。因此我有以下代码:
np.random.seed(42)
y = np.random.randint(0,5,size=(100, 2))
df = pd.DataFrame(y, columns=list('AB'))
df.groupby('A').count().agg(['max','idxmax'])
这个的输出:
B
max 28
idxmax 3
也就是说,第 3 组的行数最多。最大值为 28。
我想要以下带有命名聚合的输出:
Max ID
28 3
我的解决方案尝试:
np.random.seed(42)
y = np.random.randint(0,5,size=(100, 2))
df = pd.DataFrame(y, columns=list('AB'))
df.groupby('A').count().agg(Max=('B','max'), ID=('B','idxmax'))
这会引发以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-113-dcd54f9ab49e> in <module>
2 y = np.random.randint(0,5,size=(100, 2))
3 df = pd.DataFrame(y, columns=list('AB'))
----> 4 df.groupby('A').count().agg(Max=('B','max'),ID=('B','idxmax'))
TypeError: aggregate() missing 1 required positional argument: 'func'
如果我删除 count() 函数,那么命名聚合似乎可以工作。但是当然,它不是在计算我想要计算的内容。
我想让这个工作,因为我的解决方法看起来很混乱:
np.random.seed(42)
y = np.random.randint(0,5,size=(100, 2))
df = pd.DataFrame(y, columns=list('AB'))
df.groupby('A').count().agg(['max','idxmax']).T.reset_index(drop=True).rename(columns={'max':'Max',
'idxmax':'ID'})
输出:
Max ID
0 28 3
熊猫版本 1.0.5。
【问题讨论】:
-
需要 as_index=False 参数 -
df.groupby('A', as_index=False).count().agg(Max=('B','max'),ID=('B','idxmax')).T -
@Chris 这会引发与我相同的错误
标签: python pandas count pandas-groupby