将嵌套字典作为一行添加到多索引数据框架中

时间:2017-06-15 19:40:58

标签: python pandas dictionary multi-index

我想创建一个3级多索引pandas DataFrame like the one found in this Stack Overflow question,但我希望能够在创建DataFrame后添加新​​数据。

以下是链接帖子的多索引数据框架。为清晰起见,我已重命名较低的列级别。

AA           BB
   A     B     A     B
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6

我将传递给它的数据将是以下列形式的嵌套字典:

dictionary = {'AA': {'A': {'a': [9],
                           'b': [8]},
                     'B': {'a': [6],
                           'b': [2]}},
              'BB': {'A': {'a': [3],
                           'b': [8]},
                     'B': {'a': [1],
                           'b': [3]}}}

知道我怎么能做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您可以将新数据转换为链接帖子中描述的数据框,然后使用pd.concat将其与原始数据框合并。

使用您的示例:

df
Out[127]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6

newrow
Out[129]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  9  8  6  2  3  8  1  3

pd.concat([df, newrow])
Out[130]: 
  AA          BB         
   A     B     A     B   
   a  b  a  b  a  b  a  b
0  2  2  2  2  2  2  2  2
1  3  3  3  3  3  3  3  3
2  4  4  4  4  4  4  4  4
3  5  5  5  5  5  5  5  5
4  6  6  6  6  6  6  6  6
0  9  8  6  2  3  8  1  3