【问题标题】:How to convert each nested dictionary' element to a new pandas column?如何将每个嵌套字典的元素转换为新的 pandas 列?
【发布时间】:2021-05-05 01:25:53
【问题描述】:

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

有什么想法吗?提前谢谢!

【问题讨论】:

  • df[['id']].join(pd.DataFrame(df['info'].explode().tolist()) 试试这个,因为我无法复制你的问题
  • @anky 我收到了这个错误:TypeError: object of type 'float' has no len()
  • 给我们print(df.head()),因为我只是猜到了
  • @anky print(df.head()) 与我最初发布的内容相同

标签: python pandas dataframe dictionary nested


【解决方案1】:
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 和您的数据框连接起来以给出最终结果。

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2019-12-09
    • 1970-01-01
    • 2023-01-17
    • 2018-10-26
    • 1970-01-01
    • 2021-06-26
    • 2013-11-16
    • 2019-04-08
    相关资源
    最近更新 更多