嵌套字典到MultiIndex pandas DataFrame(3级) [英] Nested Dictionary to MultiIndex pandas DataFrame (3 level)
本文介绍了嵌套字典到MultiIndex pandas DataFrame(3级)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于三层嵌套字典,我想做到这一点
I would like to do the equivalent of this for a 3 level nested dictionary
推荐答案
以三级字典为例
In [1]: import pandas as pd
In [2]: dictionary = {'A': {'a': {1: [2,3,4,5,6],
...: 2: [2,3,4,5,6]},
...: 'b': {1: [2,3,4,5,6],
...: 2: [2,3,4,5,6]}},
...: 'B': {'a': {1: [2,3,4,5,6],
...: 2: [2,3,4,5,6]},
...: 'b': {1: [2,3,4,5,6],
...: 2: [2,3,4,5,6]}}}
以及以下基于您所链接问题中的字典的字典理解
And the following dictionary comprehension based on the one from the question you linked
In [3]: reform = {(level1_key, level2_key, level3_key): values
...: for level1_key, level2_dict in dictionary.items()
...: for level2_key, level3_dict in level2_dict.items()
...: for level3_key, values in level3_dict.items()}
哪个给
In [4]: reform
Out[4]:
{('A', 'a', 1): [2, 3, 4, 5, 6],
('A', 'a', 2): [2, 3, 4, 5, 6],
('A', 'b', 1): [2, 3, 4, 5, 6],
('A', 'b', 2): [2, 3, 4, 5, 6],
('B', 'a', 1): [2, 3, 4, 5, 6],
('B', 'a', 2): [2, 3, 4, 5, 6],
('B', 'b', 1): [2, 3, 4, 5, 6],
('B', 'b', 2): [2, 3, 4, 5, 6]}
对于熊猫DataFrame
For pandas DataFrame
In [5]: pd.DataFrame(reform)
Out[5]:
A B
a b a b
1 2 1 2 1 2 1 2
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
In [6]: df = pd.DataFrame(reform).T
Out[6]:
0 1 2 3 4
A a 1 2 3 4 5 6
2 2 3 4 5 6
b 1 2 3 4 5 6
2 2 3 4 5 6
B a 1 2 3 4 5 6
2 2 3 4 5 6
b 1 2 3 4 5 6
2 2 3 4 5 6
如您所见,您可以通过添加 理解的另一行和元组的新键.
As you can see, you could increase the number of levels easily by adding another line to the comprehension and new key to tuple.
奖金:为索引添加名称
In [7]: names=['level1', 'level2', 'level3']
In [8]: df.index.set_names(names, inplace=True)
In [9]: df
Out[9]:
0 1 2 3 4
level1 level2 level3
A a 1 2 3 4 5 6
2 2 3 4 5 6
b 1 2 3 4 5 6
2 2 3 4 5 6
B a 1 2 3 4 5 6
2 2 3 4 5 6
b 1 2 3 4 5 6
2 2 3 4 5 6
这篇关于嵌套字典到MultiIndex pandas DataFrame(3级)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文