[row_index,[elements]]`的嵌套列表到Pandas数据框?

时间:2018-09-14 22:46:16

标签: python python-3.x pandas dataframe nested

我的列表为:

list1= [[1, ['dog', 'slow']], 
        [1, [5, 4]], 
        [1, ['mice', 'cat']], 
        [2, ['cat', 'fast']], 
        [2, [6, 6]], 
        [2, ['cat', 'mice']],
        [3, ['tree', 'hurry']], 
        [3, [7, 5]], 
        [3, ['mice', 'cat']]]

我想从这个嵌套列表中形成一个数据框。我希望输出如下:

col0       col1            col2         col3
 1    ['dog', 'slow']     [5, 4]   ['mice', 'cat']
 2    ['cat', 'fast']     [6, 6]   ['cat', 'fast']
 3    ['tree', 'hurry']   [7, 5]   ['mice', 'cat']

1 个答案:

答案 0 :(得分:1)

您可以使用defaultdict(我假设1, 2, 3 ...等是您的索引):

设置

from collections import defaultdict    
dct = defaultdict(list)

for k, v in list1:
    dct[k].append(v)

pd.DataFrame.from_dict(dct, orient='index').rename(columns=lambda x: f'col{x+1}')

            col1    col2         col3
1    [dog, slow]  [5, 4]  [mice, cat]
2    [cat, fast]  [6, 6]  [cat, mice]
3  [tree, hurry]  [7, 5]  [mice, cat]