【问题标题】:How to flatten multiple dictionary objects inside a list in pandas column?如何在熊猫列的列表中展平多个字典对象?
【发布时间】:2019-07-21 09:21:04
【问题描述】:

我有一个 df,其列如下所示:

col1

[{'value':'2019-02-02'},{'value':'test1'},{'value':'test2'},{'value':'test3'},{'value':'test4'},{'value':'test5'},{'value':'test6'}]

如何展平此列,使其看起来像这样:

col1         col2
value        2019-02-02
value        test1
value        test2
value        test3
value        test4
value        test5
value        test6

我正在尝试这个:

df['Col1'] = [x[0]['value'] for x in df['Col1']]

这只是在所有嵌套字典中选择第一个值并像这样创建 df:

col1
2019-02-02
2019-02-02
2019-02-02
2019-02-02

【问题讨论】:

    标签: python-3.x pandas flatten


    【解决方案1】:

    使用tolist,然后我们需要concat 和每个pd.DataFrame(sublist)

    pd.concat([pd.DataFrame(sublist) for sublist in df.col1.tolist()]).stack().reset_index(level=1)
    Out[22]: 
      level_1           0
    0   value  2019-02-02
    1   value       test1
    2   value       test2
    3   value       test3
    4   value       test4
    5   value       test5
    6   value       test6
    0   value  2019-02-02
    1   value       test1
    2   value       test2
    3   value       test3
    4   value       test4
    5   value       test5
    6   value       test6
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2018-11-21
      • 2021-08-19
      • 2022-01-24
      • 2020-09-06
      • 1970-01-01
      • 2021-02-03
      • 2019-08-20
      • 2021-12-01
      相关资源
      最近更新 更多