如何从将(列、行)索引对映射到值的字典中创建数据框?

问题描述 投票:0回答:1

使用 pandas,给定这个以元组为键的字典:

dictionary = {(a,c): 1, (a,d): 3, (b,c): 2, (b,d): 4}

我怎样才能得到这样的数据框?

a b
c 1 2
d 3 4

我考虑过使用

df.at[]
为每个行/列位置分配正确的值 - 例如
df.at[a,c] = 1
。 但是,我不清楚如何将元组与
.at[]
一起使用。

python pandas dataframe dictionary tuples
1个回答
0
投票

您可以循环遍历字典并创建一个新的字典字典,其中外部字典的键是列名称,内部字典的键是行索引。为了节省几行代码,我将使用

defaultdict(dict)
作为外部字典

from collections import defaultdict
import pandas as pd

dictionary = {('a','c'): 1, ('a','d'): 3,
              ('b','c'): 2, ('b','d'): 4}


dd = defaultdict(dict)

for (col_name, row_name), value in dictionary.items():
    dd[col_name][row_name] = value

这会产生以下结果

dd

defaultdict(<class 'dict'>, {'a': {'c': 1, 'd': 3}, 'b': {'c': 2, 'd': 4}})

最后,用它来创建你的数据框:

df = pd.DataFrame.from_dict(dd)

这给出了所需的数据框:

   a  b
c  1  2
d  3  4
© www.soinside.com 2019 - 2024. All rights reserved.