python - 如何将每个嵌套字典的元素转换为新的 pandas 列?
问题描述
我有以下熊猫数据框结构。有两 (2) 列:id
和info
(object)
id info
0 14050000893760073 [{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]
我想将此格式转换为以下格式:
id route_id stop_id
0 14050000893760073 1 1
1 14050000893760073 2 2
有任何想法吗?先感谢您!
解决方案
df2 = df.explode('info', ignore_index=True)
df2
id info
0 14050000893760073 {'route_id': '1', 'stop_id': '1'}
1 14050000893760073 {'route_id': '2', 'stop_id': '2'}
info_df = df2["info"].apply(pd.Series)
info_df
route_id stop_id
0 1 1
1 2 2
result = pd.concat([df2, info_df], axis=1).drop('info', axis=1)
result
id route_id stop_id
0 14050000893760073 1 1
1 14050000893760073 2 2
首先,分解列中的列表info
。然后,您从该列创建一个数据系列。最后,您将info_df
和您的数据框连接起来以给出最终结果。
推荐阅读
- php - Laravel:从今天开始查询所有带有时间戳的记录
- php - php中的CDN链接包含文件
- github - im having trouble with git push ive t
- syntax-error - ocaml中二叉搜索树的语法错误
- python - creating a function that takes in a string and returns that string with every even letter uppercase
- javascript - 如何有效地编辑数据集中深处的项目,显示为反应组件?
- java - 在 Intellij Idea 中禁用 java doc 自动格式化。2019
- c++ - 在 C++ 中,是否可以从类成员函数返回类的元素?
- c# - Visual Studio 错误:“Microsoft.ACE.OLEDB.12.0”提供程序未在本地计算机上注册
- php - PHP foreach 数组并与 GET 进行比较