简体   繁体   English

从多级字典创建平面 dataframe 的最佳(和最快)方法是什么

[英]What is the nicest (and fastest) way to create a flat dataframe from a multilevel dictionary

I have a dictionary that looks like that:我有一本看起来像这样的字典:

dic = {'a': {'b': [1,2], 'c': [3,4]}, 'A': {'B': [10,20], 'C': [30, 40]}}

I would like to get a 2 dim dataframe with 3 columns that looks like that:我想得到一个 2 暗的 dataframe 与 3 列看起来像这样:

'a' 'b'  1  
'a' 'b'  2  
'a' 'c'  3  
'a' 'c'  4  
'A' 'B'  10  
'A' 'B'  20  
'A' 'C'  30  
'A' 'C'  40  

IIUC国际大学联盟

s=pd.DataFrame(d).stack().explode().reset_index()
  level_0 level_1   0
0       b       a   1
1       b       a   2
2       c       a   3
3       c       a   4
4       B       A  10
5       B       A  20
6       C       A  30
7       C       A  40

Using list comprehension:使用列表理解:

import pandas as pd

dic = {'a': {'b': [1,2], 'c': [3,4]}, 'A': {'B': [10,20], 'C': [30, 40]}}

data = [
    (val_1, val_2, val_3)
    for val_1, nest_dic in dic.items()
    for val_2, nest_list in nest_dic.items()
    for val_3 in nest_list
]
df = pd.DataFrame(data)

print(df)
# Output:
#    0  1   2
# 0  a  b   1
# 1  a  b   2
# 2  a  c   3
# 3  a  c   4
# 4  A  B  10
# 5  A  B  20
# 6  A  C  30
# 7  A  C  40

Like this maybe:可能像这样:

In [1845]: pd.concat({k: pd.DataFrame(v).T for k, v in dic.items()},axis=0).reset_index()                                                                                                                   
Out[1845]: 
  level_0 level_1   0   1
0       a       b   1   2
1       a       c   3   4
2       A       B  10  20
3       A       C  30  40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个由多个数据帧制成的多级 pandas dataframe 的最快方法是什么? - What is the fastest way to create one a multilevel pandas dataframe made from multiple dataframes? 以最快的方式从 dataframe Python 中的索引创建一个新的字典列表 - Create a new list of dictionary from the index in dataframe Python with the fastest way 从python中的平面字典创建嵌套字典的通用方法 - Generic way to create nested dictionary from flat dictionary in python 从列表制作DataFrame的最快方法是什么? - What is the fastest way to make a DataFrame from a list? 使用最快且可扩展的方式从另一个字典创建字典 - Create dictionary from another dictionary with the fastest and scalable way 从python中的平面列表创建嵌套字典的通用方法 - Generic way to create nested dictionary from flat list in python 替换字典中文件行的最快方法是什么? - python - What is the fastest way to replace lines of a file from a dictionary? 将大字典转换为数据框的最快方法 - Fastest way to convert huge dictionary to a dataframe 在numpy数组中对飞机进行加权的最好方法是什么? - What is the nicest way to weight planes in a numpy array? 有没有办法从列表中的字典创建 dataframe? - Is there a way to create a dataframe from a Dictionary inside a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM