首页 > 解决方案 > 如何将每个嵌套字典的元素转换为新的 pandas 列?

问题描述

我有以下熊猫数据框结构。有两 (2) 列:idinfo(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

有任何想法吗?先感谢您!

标签: pythonpandasdataframedictionarynested

解决方案


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和您的数据框连接起来以给出最终结果。


推荐阅读