使用元组键(key1,key2)将字典转换为数据帧,当key1是索引和key2时,value是列

时间:2016-12-19 15:01:10

标签: python-2.7 pandas dictionary dataframe multi-index

我有以下词典:dict = {('one','A'):8,('one','B'):19,('one','D'):29,('two','C'):18,('two','A'):10,('two','B'):4,('two','D'):2,('six','C'):4,('six','A'):4,('six','B'):4}

我将其转换为dataFrame,如下所示:

         Score
one  A     8
     B    19
     D    29
two  C    18
     A    10
     B     4
     D     2
six  C     4
     A     4
     B     4

但是我想将字典转换为DF,其中来自元组的Key1是索引,而key2是列名:

A B C D
one 8 19 0 29 two 10 4 18 2 six 4 4 4 0

如何将字典转换为此类数据框?

3 个答案:

答案 0 :(得分:1)

unstack的解决方案:

d = {('one','A'):8,('one','B'):19,('one','D'):29,('two','C'):18,
    ('two','A'):10,('two','B'):4,('two','D'):2,('six','C'):4,
    ('six','A'):4,('six','B'):4}

idx = pd.MultiIndex.from_tuples(d.keys())
print (pd.DataFrame(list(d.values()), index=idx, columns=['Score'])
         .unstack(fill_value=0)['Score'])

      A   B   C   D
one   8  19   0  29
six   4   4   4   0
two  10   4  18   2

答案 1 :(得分:0)

试试这个:

In [31]: pd.DataFrame({'Score':list(t.values())}, index=pd.MultiIndex.from_tuples(t.keys())).reset_index().pivot_table(index='level_0', columns='leve
    ...: l_1', fill_value=0).reset_index(level=0, drop=True)
Out[31]:
        Score
level_1     A   B   C   D
0           8  19   0  29
1           4   4   4   0
2          10   4  18   2

答案 2 :(得分:0)

你可以试试这个:,它的上一个版块的更新版本:

df = (pd.DataFrame({'Score':list(dict.values())}, 
             index=pd.MultiIndex.from_tuples(dict.keys())).reset_index()
             .pivot_table(index='level_0', columns='level_1', fill_value=0).reset_index())

df.columns = df.columns.droplevel(0)
df = df.rename(columns={'':'index'}).set_index('index')