【问题标题】:How to convert a list with dictionaries into new pandas columns?如何将带有字典的列表转换为新的熊猫列?
【发布时间】:2021-01-25 16:54:33
【问题描述】:

我有一个数据框,其中有一个字典列表作为一列:此列具有以下格式:

[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]

如何将此列转换为 4 个新列?我的意思是:route_id (x2), stop_id(x2) 作为新列。

提前致谢!

【问题讨论】:

  • 您想要 4 个新列还是 2 个?您能否发布一个具有预期输出的输入数据帧示例?

标签: python pandas list dataframe dictionary


【解决方案1】:

您可以将df.explodedf.apply 一起使用:

In [275]: df = pd.DataFrame({'A': [[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]]})

In [276]: df
Out[276]: 
                                                   A
0  [{'route_id': '1', 'stop_id': '1'}, {'route_id...

In [284]: df['A'].explode().apply(pd.Series)
Out[284]: 
  route_id stop_id
0        1       1
0        2       2

【讨论】:

  • 谢谢! @Mayank
猜你喜欢
  • 2021-09-07
  • 2021-10-24
  • 2019-07-29
  • 2016-09-06
  • 1970-01-01
  • 2017-12-12
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多