【问题标题】:pandas: how to convert list of list into series of list?pandas:如何将列表列表转换为列表系列?
【发布时间】:2022-01-24 08:29:18
【问题描述】:

我在 python 中有一个字典,每个键都有一个嵌套列表的值,如下所示:

test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3],[4,5,6]]}

我想将字典键转换为 pandas 中的数据框列名,并将嵌套列表转换为一系列列表,如下所示:

'x' 'y'
[1,2,3] [1,2,3]
[4,5,6] [4,5,6]

有什么办法吗?

【问题讨论】:

    标签: python pandas list dictionary


    【解决方案1】:

    试试:

    import pandas as pd
    df = pd.DataFrame(test)
    print(df)
    

    这是我 ide 中的输出:

    如果您想将 Dataframe 保存到 csv 文件中,您应该:

    output_name = 'myfile.csv'
    df.to_csv(output_name)
    

    这将为您的工作目录中的 excel 类文件创建一个 csv 通用名称。 您可以通过以下方式检查它的存在:

    import os
    os.listdir()
    

    【讨论】:

    • 澄清:这只能是因为x 和y 具有相同的长度。 pd.DataFrame({'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3]]}) 提高 ValueError: All arrays must be of the same length
    • 正确,如果您需要创建字典值确实具有不同长度的数据框,请参阅:stackoverflow.com/a/19736406/15488129
    【解决方案2】:

    只需将其转换为数据框,此代码即可返回您需要的内容。

    import pandas as pd
    import numpy as np
    
    test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3],[4,5,6]]}
    df = pd.DataFrame(test)
    

    这将返回以下内容:

               x          y
    0  [1, 2, 3]  [1, 2, 3]
    1  [4, 5, 6]  [4, 5, 6]
    

    然后您可以将其转换为 csv 文件并设置 index=False 以删除行号(在本例中为 0 和 1):

    df.to_csv('df.csv', index=False)
    

    这应该会给你如下输出:

     x          y
    [1, 2, 3]  [1, 2, 3]
    [4, 5, 6]  [4, 5, 6]
    

    【讨论】:

      【解决方案3】:

      试试这个:
      pd.DataFrame(columns =test.keys() ,data = test.values())

      它解决了@girolamo 的回答引发的 Value 错误。

      对于 test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3]]}

      它给出输出:

      也就是说,如果 x 和 y 的 len 不同,则返回 None

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 2019-04-21
        • 2013-02-13
        • 2019-11-28
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        相关资源
        最近更新 更多