[英]Adding nested dictionaries as a row into Multi-Indexed DataFrame
I would like to create a 3-level Multi-Indexed pandas DataFrame much like the one found in this Stack Overflow question but I would like to be able to add new data after the DataFrame has been created. 我想创建一个三级多索引熊猫DataFrame, 就像在此Stack Overflow问题中找到的那样,但是我希望能够在创建DataFrame之后添加新数据。
Here is the Multi-Indexed DataFrame from the linked post. 这是链接文章中的Multi-Indexed DataFrame。 I have renamed the lower column levels for clarity.
为了清楚起见,我已将较低的列级别重命名。
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
The data that I will be passing to it will be a nested dictionary in the following form: 我将传递给它的数据将是以下形式的嵌套字典:
dictionary = {'AA': {'A': {'a': [9],
'b': [8]},
'B': {'a': [6],
'b': [2]}},
'BB': {'A': {'a': [3],
'b': [8]},
'B': {'a': [1],
'b': [3]}}}
Any idea how I can accomplish this? 知道我该如何做到吗?
You could transform the new data into a dataframe as described in the linked post, then use pd.concat
to combine it with the original dataframe. 您可以按照链接文章中的描述将新数据转换为数据
pd.concat
,然后使用pd.concat
将其与原始数据pd.concat
组合。
Using your example: 使用您的示例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.