首页 > 解决方案 > 将包含不同长度列表的字典转换为 2 列数据框

问题描述

我有一本像这样的字典

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]

第二列包括数字列表。有什么建议么?

标签: pythonpandaslistdataframedictionary

解决方案


#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]

推荐阅读