我有两本字典词典:
d_old = {person1: {a1:aaa, b1:bbb, c1:ccc...}, person2:{...}, ...}
d_new = {person1: {a1:AAA, b1:BBB, c1:CCC...}, person2:{...}, ...}
我想在pandas DataFrame中将它们彼此相邻,使用层次化的MultiIndexing来创建这样的东西:
d_old d_new
person1 a1 aaa AAA
b1 bbb BBB
c1 ccc CCC
person2 a1 ...
我是熊猫的新手,虽然我可以为单个字典进行多索引工作,但我还是试图调整这两个字典。怎么做?
...另外,我无法正确格式化上表,如果您知道如何,请随意将此问题编辑为更易读的形式。
答案 0 :(得分:3)
您可以concat
使用unstack
ed DataFrames
:
d_old = {'person1': {'a1':'aaa', 'b1':'bbb', 'c1':'ccc'},
'person2':{'a1':'cc', 'b1':'dd', 'c1':'ee'},}
d_new = {'person1': {'a1':'AAA', 'b1':'BBB', 'c1':'CCC'},
'person2':{'a1':'AAA', 'b1':'BBB', 'c1':'CCC'}}
df1 = pd.DataFrame(d_old)
df2 = pd.DataFrame(d_new)
print(df1)
print(df2)
print (pd.concat([df1.unstack(), df2.unstack()], keys=['df_old','df_new'], axis=1))
df_old df_new
person1 a1 aaa AAA
b1 bbb BBB
c1 ccc CCC
person2 a1 cc AAA
b1 dd BBB
c1 ee CCC