agg 与aggregate 相同。它的可调用是传递DataFrame 的列(Series 对象),一次一个。
您可以使用idxmax 来收集最大行的索引标签
计数:
idx = df.groupby('word')['count'].idxmax()
print(idx)
产量
word
a 2
an 3
the 1
Name: count
然后使用loc 选择word 和tag 列中的那些行:
print(df.loc[idx, ['word', 'tag']])
产量
word tag
2 a T
3 an T
1 the S
注意idxmax 返回索引标签。 df.loc 可用于选择行
按标签。但是,如果索引不是唯一的——也就是说,如果存在具有重复索引标签的行——那么df.loc 将选择 所有行 与idx 中列出的标签。因此,如果您将idxmax 与df.loc 一起使用,请注意df.index.is_unique 是True
或者,您可以使用apply。 apply 的可调用对象传递了一个子数据帧,它使您可以访问所有列:
import pandas as pd
df = pd.DataFrame({'word':'a the a an the'.split(),
'tag': list('SSTTT'),
'count': [30, 20, 60, 5, 10]})
print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
产量
word
a T
an T
the S
使用idxmax 和loc 通常比apply 快,尤其是对于大型DataFrame。使用 IPython 的 %timeit:
N = 10000
df = pd.DataFrame({'word':'a the a an the'.split()*N,
'tag': list('SSTTT')*N,
'count': [30, 20, 60, 5, 10]*N})
def using_apply(df):
return (df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
def using_idxmax_loc(df):
idx = df.groupby('word')['count'].idxmax()
return df.loc[idx, ['word', 'tag']]
In [22]: %timeit using_apply(df)
100 loops, best of 3: 7.68 ms per loop
In [23]: %timeit using_idxmax_loc(df)
100 loops, best of 3: 5.43 ms per loop
如果你想要一个将单词映射到标签的字典,那么你可以使用set_index
和to_dict 像这样:
In [36]: df2 = df.loc[idx, ['word', 'tag']].set_index('word')
In [37]: df2
Out[37]:
tag
word
a T
an T
the S
In [38]: df2.to_dict()['tag']
Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'}