agg与相同
aggregate。可调用的是一次传递一次的列(
Series对象)
Dataframe。
您可以
idxmax用来收集具有最大计数的行的索引标签:
idx = df.groupby('word')['count'].idxmax()print(idx)产量
worda 2an 3the 1Name: count
然后用于
loc在
word和
tag列中选择那些行:
print(df.loc[idx, ['word', 'tag']])
产量
word tag2 a T3 an T1 the S
请注意,
idxmax返回索引 标签
。
df.loc可用于按标签选择行。但是,如果索引不是唯一的-即,如果存在带有重复索引标签的行-
df.loc则将选择带有标签的
所有行
idx。所以,要小心,
df.index.is_unique是
True如果你使用
idxmax与
df.loc
或者,您可以使用
apply。
apply的callable传递了一个sub-Dataframe,它使您可以访问所有列:
import pandas as pddf = 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()]))产量
worda Tan Tthe S
使用
idxmax和
loc通常比快
apply,尤其是对于大型Dataframe。使用IPython的%timeit:
N = 10000df = 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 loopIn [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]: df2Out[37]: tagword a Tan Tthe SIn [38]: df2.to_dict()['tag']Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'}


