[英]Efficient way to group pandas dataframe rows by a list of tags in a column
[英]Pandas Dataframe group by, column with a list
我使用 jupyter 筆記本,我當前的數據框如下所示:
players_mentioned | tweet_text | polarity
______________________________________________
[Mane, Salah] | xyz | 0.12
[Salah] | asd | 0.06
如何將所有玩家單獨分組並平均他們的極性?
目前我嘗試使用:
df.groupby(df['players_mentioned'].map(tuple))['polarity'].mean()
但這將返回一個數據框,將所有提及的內容分組在一起以及分開時,我如何最好地將玩家分開,然后將它們重新組合在一起。
預期輸出將包含
player | polarity_average
____________________________
Mane | 0.12
Salah | 0.09
換句話說,如何按每行列表中的每個項目進行分組。
如果您只是想按players_提到的分組並獲得該球員受歡迎度得分的平均值,則應該這樣做。
df.groupby('players_mentioned').polarity.agg('mean')
您可以使用此答案中的unnesting
習語。
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
您現在可以在未嵌套的“players_提到”列上調用groupby
。
(unnesting(df, ['players_mentioned'])
.groupby('players_mentioned', as_index=False).mean())
players_mentioned polarity
0 Mane 0.12
1 Salah 0.09
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.