栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python pandas,DF.groupby()。agg(),agg()中的列引用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python pandas,DF.groupby()。agg(),agg()中的列引用

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'}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624694.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号