python - 将带有项目列表的字典转换为 Pandas 数据框

我有以下字典:

print(d)

{1: ([4, 3, 2], [10.0, 6.666666666666667, 7.5]),
 2: ([4, 3, 2], [6.0, 6.666666666666667, 8.5]),
 3: ([4, 3, 2], [26.0, 29.666666666666668, 7.5])}

我想转换成 pandas df。我还想指定列名。 Col1 应该是字典的键。 输出应如下所示(不需要四舍五入):

col1  col2  col3  
 1     4     10
 1     3     6.6
 1     2     7.5
 2     4     6
 2     3     6.6
 2     2     8.5
 3     4     26
 3     3     29.6
 3     2     7.5

我试过这个:

pd.DataFrame.from_dict(d, orient='index')

但这会导致一个以列表作为列值的 df

    0                                       1
1   [4, 3, 2]   [10.0, 6.666666666666667, 7.5]
2   [4, 3, 2]   [6.0, 6.666666666666667, 8.5]
3   [4, 3, 2]   [26.0, 29.666666666666668, 7.5]
4   [4, 3, 2]   [5.25, 5.333333333333333, 6.0]

最佳答案

我们可以展平字典来创建代表数据帧行的三元组

df = pd.DataFrame([(k, *t) for k, v in d.items() for t in zip(*v)])

   0  1          2
0  1  4  10.000000
1  1  3   6.666667
2  1  2   7.500000
3  2  4   6.000000
4  2  3   6.666667
5  2  2   8.500000
6  3  4  26.000000
7  3  3  29.666667
8  3  2   7.500000

https://stackoverflow.com/questions/67321231/

相关文章:

c++ - 使用具有非 constexpr 值的 int 模板函数

r - 将字符串拆分为单词并分配给新列

flutter - 为什么 SliverFillRemaining 膨胀得太多了?

svg - 如何配置在 sveltekit 中使用 svg 文件?

powerbi - Multi-Tenancy 场景下如何访问power BI Service

javascript - 选择选项后如何取消突出显示选择元素?

python - 仅当 "Lossless"时才转换为整数?

matlab - 如何使用 matlab 正确绘制矢量线性方程?

http - 使用 Clack/ningle 在 Web 服务器中嵌入图像

python - PyCharm 看不到项目中的文件