午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

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

瀏覽:22日期:2022-08-07 13:10:43
如何解決python pandas,DF.groupby()。agg(),agg()中的列引用?

agg與相同aggregate。可調(diào)用的是一次傳遞一次的列(Series對(duì)象)DataFrame。

您可以idxmax用來(lái)收集具有最大計(jì)數(shù)的行的索引標(biāo)簽:

idx = df.groupby(’word’)[’count’].idxmax()print(idx)

產(chǎn)量

worda 2an 3the 1Name: count

然后用于loc在word和tag列中選擇那些行:

print(df.loc[idx, [’word’, ’tag’]])

產(chǎn)量

word tag2 a T3 an T1 the S

請(qǐng)注意,idxmax返回索引 標(biāo)簽。df.loc可用于按標(biāo)簽選擇行。但是,如果索引不是唯一的-即,如果存在帶有重復(fù)索引標(biāo)簽的行-df.loc則將選擇帶有標(biāo)簽的所有行idx。所以,要小心,df.index.is_unique是True如果你使用idxmax與df.loc

或者,您可以使用apply。apply的callable傳遞了一個(gè)sub-DataFrame,它使您可以訪問(wèn)所有列:

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()]))

產(chǎn)量

worda Tan Tthe S

使用idxmax和loc通常比快apply,尤其是對(duì)于大型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

如果你想有一個(gè)字典映射字標(biāo)簽,那么你可以使用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’}解決方法

關(guān)于一個(gè)具體問(wèn)題,說(shuō)我有一個(gè)DataFrame DF

word tag count0 a S 301 the S 202 a T 603 an T 54 the T 10

我想 為每個(gè)“單詞” 找到 具有最多“計(jì)數(shù)”的“標(biāo)簽” 。因此,回報(bào)將類似于

word tag count1 the S 202 a T 603 an T 5

我不在乎計(jì)數(shù)列或訂單/索引是原始的還是混亂的。返回字典{ ‘the’:’S’ ,…}很好。

我希望我能做

DF.groupby([’word’]).agg(lambda x: x[’tag’][ x[’count’].argmax() ] )

但這不起作用。我無(wú)法訪問(wèn)列信息。

更抽象地講, agg( function 中的 函數(shù) 將其視為 __什么?

順便說(shuō)一句,.agg()與.aggregate()相同嗎?

非常感謝。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 久久精品一区二区三区四区 | 国产欧美精品区一区二区三区 | www.国产在线观看 | 青青操在线观看 | 精品一区二区视频在线观看 | 日韩啪啪网| 国产一区二区在线观看视频 | 成人午夜激情视频 | 成人午夜视频网站 | 五月婷婷婷婷 | 国产精品中文字幕在线观看 | 欧美午夜久久 | 色图色小说| 一级片久久久 | 亚洲男人天堂2019 | 免费看黄色一级视频 | 免费在线日本 | 成人免费一级片 | 99久久久久成人国产免费 | 国产精品理论片 | 日韩不卡一区 | 国产极品在线播放 | 污视频在线免费观看 | 日韩三级高清 | 免费成人深夜夜行网站 | 国产免费a | 伊人亚洲综合 | 亚洲日本中文字幕 | 在线观看黄 | 日本wwwwww| 国内激情自拍 | 久久嫩草精品久久久久 | 亚洲精品久久久久久国 | 天天躁日日躁狠狠躁 | 国产精品亚洲一区 | 午夜激情国产 | 欧美一级免费视频 | 日韩欧美国产高清91 | 日韩女优在线播放 | 最好看的2019年中文在线观看 | 午夜精品久久久久久久久久久久 |