[英]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.