python-3.x - 将 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"
... , ..., ...
我希望这能带来一些清晰
解决方案
使用此代码,
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]
推荐阅读
- vmware-clarity - 访问具有以下堆栈的分页网格中的页面时,VMWare Clarity 崩溃
- ansible - 如何确保 ansible playbook 使用来自不同文件的主机名或从命令行使用它?
- node.js - 尝试使用 node.js 和 exec + aws cli 将所有文件从一个 S3 存储桶移动到另一个存储桶
- flutter - 如何在全球使用这种方法?
- postgresql - 将表中的行连接并连接到字符串中
- java - Jersey @FormDataParam 读取多个 InputStream 文件
- kubernetes - 如何为 devops 管道认证和访问 Kubernetes 集群?
- kubernetes - 使用 Terraform 启用 Stackdriver Kubernetes Engine 监控
- angular - 将 firestore 添加到 Angular 组件构造函数会引发 No provider 错误
- amazon-web-services - 如何根据 SQS 消息级别进行缩放