列表值字典中的Pandas数据框

oww*_*w14 8 python dictionary list dataframe pandas

我有一本字典,其中的列表如:

cols = {'animals':['dog','cat','fish'],
        'colors':['red','black','blue','dog']}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为一个数据框,其中每个列表根据其键枚举,结果为

key variable
animals dog
animals cat
animal fish
colors red
colors black
colors blue
colors dog
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经做到了这一点:但是它并没有为我提供理想的结果。

cols_df = pd.DataFrame.from_dict(cols, orient='index')
Run Code Online (Sandbox Code Playgroud)

我该如何修改以达到上述目的?

Bal*_*Ben 8

无导入,适用于所有输入:

>>> pd.DataFrame([(key, var) for (key, L) in cols.items() for var in L], 
                 columns=['key', 'variable'])

       key variable
0  animals      dog
1  animals      cat
2  animals     fish
3   colors      red
4   colors    black
5   colors     blue
6   colors      dog
Run Code Online (Sandbox Code Playgroud)


jpp*_*jpp 0

使用itertools.chainitertools.repeat

import pandas as pd
from itertools import chain, repeat

chainer = chain.from_iterable

d = {'animals': ['dog', 'cat', 'fish'],
     'colors': ['red', 'black', 'blue', 'dog']}

df = pd.DataFrame({'key': list(chainer(repeat(k, len(v)) for k, v in d.items())),
                   'variable': list(chainer(d.values()))})

print(df)

       key variable
0  animals      dog
1  animals      cat
2  animals     fish
3   colors      red
4   colors    black
5   colors     blue
6   colors      dog
Run Code Online (Sandbox Code Playgroud)