久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:2日期:2022-08-07 13:10:43
如何解決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’}解決方法

關于一個具體問題,說我有一個DataFrame DF

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

我想 為每個“單詞” 找到 具有最多“計數”的“標簽” 。因此,回報將類似于

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

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

我希望我能做

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

但這不起作用。我無法訪問列信息。

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

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

非常感謝。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 综合久久综合久久 | 国产欧美一区二区精品婷 | av在线免费观看一区二区 | 久久大陆 | 欧美一区二区三区免费 | 亚洲午夜精品一区二区三区他趣 | 亚洲午夜电影 | 国产精品高潮呻吟av久久4虎 | 欧洲精品在线观看 | 秋霞电影院午夜伦 | 亚洲欧美高清 | 亚洲精品一区二区 | 91小视频网站 | 午夜在线观看视频网站 | 亚洲视频在线免费观看 | 一级欧美 | 免费网站看v片在线a | 色综合国产| 成人一级片视频 | 国产性网 | 精品免费久久久久久久苍 | www.伊人 | 操到爽| 91视频免费观看 | 91亚洲国产成人久久精品网站 | 久草免费在线视频 | 欧美午夜精品久久久 | 精品久久久久久国产 | 99影视| 夜本色| 成人精品视频在线观看 | 国产福利在线播放 | 久久69 | 激情欧美一区二区三区中文字幕 | 免费在线观看av的网站 | 国产精品色婷婷亚洲综合看 | 综合亚洲精品 | 亚洲一区二区免费看 | 91高清视频在线观看 | 午夜国产视频 | 精品国产99 |