首页 > 解决方案 > 将 Dataframe 中的值转换为列表

问题描述

我有一个来自 Dota 中已解析匹配项的数据框,其中包含带有 match_id、插槽和文本列的聊天信息。每行代表一行文本。现在,我想对这些行进行分组,以便每个插槽(代表玩家)在值列表中分配给它们的所有文本。插槽是从 0 到 9 的数字,所以我不希望匹配号 5 中插槽 0 的文本与匹配号 1 中插槽 0 的文本组合在一起。我将如何去做?是否可以就地进行,或者我必须从头开始创建一个新的数据框?

这是一个示例输入:

match_id, slot, text
0, 0, "gg"
0, 2, "good game"
0 , 2, "good play" 1
, 0, "glhf"
1, 6, "u2"
1, 0, "thx"
. .., ..., ...

我想要的是将其总结为:

match_id, slot, text
0, 0, "gg"
0, 2, {"good game", "well playing"}
1, 0, {"glhf", "thx"}
1, 6, "u2"
... , ..., ...

我希望这能带来一些清晰

标签: python-3.xpandasdataframe

解决方案


使用此代码,

import pandas as pd
df = pd.DataFrame({'match_id' :[0,0,0,1,1,1] ,'slot':  [0,2,2,0,6,0] ,'text':  ['gg','good game','well played' ,'glff' , 'u2' , 'thx'] })
df.groupby(['match_id','slot'])['text'].apply(list).reset_index(name='text_list')

输出:

   match_id  slot            text_list
0         0     0                 [gg]
1         0     2  [game, well played]
2         1     0          [glff, thx]
3         1     6                 [u2]

推荐阅读