我有一个 dict
的 dicts
我想把它做成 Pandas
DataFrame
. dict
被构造为映射到 dict
的索引将列索引映射到它们的值,然后我想要 DataFrame
中的所有其他内容为 0。例如:
d = {0: {0:2, 2:5},
1: {1:1, 3:2},
2: {2:5}}
那么我想要 DataFrame
看起来像
index c0 c1 c2 c3
0 2.0 NaN 5.0 NaN
1 NaN 1.0 NaN 2.0
2 NaN NaN 5.0 NaN
我目前正计划编写一个函数来 yield
来自 d
中每个项目的元组并将其用作创建 DataFrame
的可迭代对象,但我想知道是否还有其他人做过类似的事情。
最佳答案
只需调用 DataFrame.from_dict
pd.DataFrame.from_dict(d,'index').sort_index(axis=1)
0 1 2 3
0 2.0 NaN 5.0 NaN
1 NaN 1.0 NaN 2.0
2 NaN NaN 5.0 NaN
关于python - 从包含映射到值的索引的字典中创建 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56746110/