首页 > 解决方案 > 从列表字典创建数据框

问题描述

我有一个 python 列表字典,我想创建一个多索引数据框

data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
pd.DataFrame.from_dict(data, orient='index')

从上面的代码得到如下输出

       0  1  2  3
row_1  3  2  1  0
row_2  a  b  c  d

我想要像下面这样的输出

       values
row_1  3 
       2  
       1
       0
row_2  a  
       b  
       c  
       d

你能帮帮我吗

标签: pythonpython-3.xpandaslist

解决方案


让我们试试stack

df = pd.DataFrame.from_dict(data, orient='index').stack()
Out[298]: 
row_1  0    3
       1    2
       2    1
       3    0
row_2  0    a
       1    b
       2    c
       3    d
dtype: object

推荐阅读