简体   繁体   English

如何将每个嵌套字典的元素转换为新的 pandas 列?

[英]How to convert each nested dictionary' element to a new pandas column?

I have the following pandas dataframe structure.我有以下 pandas dataframe 结构。 There are two (2) columns: id and info (object)有两 (2) 列: idinfo (对象)

                    id                                                                    info
0    14050000893760073  [{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]

I would like to convert this format to the following format:我想将此格式转换为以下格式:

                  id  route_id  stop_id
0  14050000893760073         1        1
1  14050000893760073         2        2

Any ideas?有任何想法吗? Thank you in advance!先感谢您!

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

First, you explode the list that you have in the info column.首先,分解info列中的列表。 Then, you create a data series out of that column.然后,您从该列创建一个数据系列。 And at last, you concatenate the info_df and your dataframe to give the final result.最后,连接info_df和 dataframe 以给出最终结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM