python - 如何从字典有效构建数据框(pandas)

标签 python list pandas dictionary dataframe

问题是这样的:

dict = {0:['A', 'B','C'], 1:'D'}

我想传输到数据框:

|index|values|
--------------
|  0  |   A  |
--------------
|  0  |   B  |
--------------
|  0  |   C  |
--------------
|  1  |   D  |
--------------

所以我的想法是将字典转换为元组列表:

dict = [(0,'A'), (0,'B'), (0,'C'), (1,'D')]

然后我可以通过以下方式创建我想要的数据框:

pd.Dataframe(dict)

对于字典转换,我一直使用的是:

为列表创建展平函数

flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]

使用列表理解来构造元组列表

pd.DataFrame(flatten([[(i,jj) for jj in j] for (i, j) in dict.items()]))

有没有更好、更有效的方法来解决这个问题?

最佳答案

首先不要将 dict 命名为 dict

然后我们看问题,我正在使用 pd.Seriesstack

pd.Series(d).apply(pd.Series).stack().reset_index(level=1,drop=True)
Out[149]: 
0    A
0    B
0    C
1    D
dtype: object

关于python - 如何从字典有效构建数据框(pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50455266/

相关文章:

C# Return Generic List/IEnumerable,它是如何工作的?

python - 如何检查 pandas DataFrame 中的列值类型

python - Pandas 如何将每个 id 的月份值相加

python - 如何根据pandas数据框中的多列值条件排除行?

python - Dockerfile在项目目录中运行python脚本文件

python - 艰苦学习Python ex20,这个函数是如何工作的?

python - 使用 .split 隔离 Python 中未定义的关键字

python - 类型错误:不支持的操作数类型 - : 'list' 和 'list'

python - 列表理解列表列表

python - 有没有办法让 Pandas ewm 在固定窗口上运行?