[英]How to convert each nested dictionary' element to a new pandas column?
我有以下 pandas dataframe 结构。 有两 (2) 列: id
和info
(对象)
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
和 dataframe 以给出最终结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.