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
中的所有行。因此,请确保如果您要使用
df.loc
进行选择,则
df.index.is_unique
为
True
。
或者,您可以使用 apply
。可调用的 apply
将传递一个子 DataFrame,从而使您可以访问所有列:
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()]))
产出(yields)
word
a T
an T
the S
使用
idxmax
和
loc
通常比
apply
更快,特别是对于大型数据框。使用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'}
df.groupby('word')['count'].idxmax()
。 - unutbu