【问题标题】:Converting a dictionary including lists with different lengths to a 2-column dataframe将包含不同长度列表的字典转换为 2 列数据框
【发布时间】:2020-08-16 02:21:09
【问题描述】:

我有一本像这样的字典

my_dict = {0:[1,2],
           1:[1, 5, 100,120],
           2:[1, 89, 90, 1625, 98, 0, 10]}

我想将它转换为只有两列的数据框。

col1 col2
0   [1, 2]
1   [1, 5, 100,120]
2   [1, 89, 90, 1625, 98, 0, 10]

第二列包含一个数字列表。有什么建议吗?

【问题讨论】:

    标签: python pandas list dataframe dictionary


    【解决方案1】:
    s=pd.Series(my_dict).reset_index()
    Out[32]: 
       index                             0
    0      0                        [1, 2]
    1      1              [1, 5, 100, 120]
    2      2  [1, 89, 90, 1625, 98, 0, 10]
    

    【讨论】:

      【解决方案2】:
      #Input dictionary
      my_dict = {0:[1,2],
                 1:[1, 5, 100,120],
                 2:[1, 89, 90, 1625, 98, 0, 10]}
      
      #Convert dictionary to dataframe
      df = pd.DataFrame(my_dict.items(),columns=["col1","col2"])
      
      print(df)
      

      输出:

         col1                          col2
      0     0                        [1, 2]
      1     1              [1, 5, 100, 120]
      2     2  [1, 89, 90, 1625, 98, 0, 10]
      

      【讨论】:

        猜你喜欢
        • 2019-08-12
        • 2019-04-21
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        相关资源
        最近更新 更多