[英]How can I convert this dictionary into a Pandas dataframe?
I have a dictionary that looks like this:我有一本看起来像这样的字典:
{'NorthernRegion': {'date': '2021-12-31',
'state': PA,
'candySales': 500,
'grocerySales': 1500,
'electronicSales': 800,
...
},
{'date': '2021-12-30',
...
},
{'date': '2021-12-29',
...
},
...
}
It is a nested dictionary.它是一个嵌套字典。 I want the nested dictionary to make up a Pandas data frame.我希望嵌套字典组成一个 Pandas 数据框。 For example, each row would be a date, and the other categories would make up the columns.例如,每一行将是一个日期,而其他类别将组成列。 What is the best way to go about this? go 关于这个的最佳方法是什么? I don't seem to be making any quality progress.我似乎没有取得任何质量进步。
The data frame would look like数据框看起来像
Date State Candy Sales Grocery Sales ...
-------------------------------------------------------
2021-12-31 PA 500 1500 ...
2021-12-30 PA 600 1600 ...
...
Each dictionary item needs a key and value, so assuming the complete structure of your dictionary looks something like the following:每个字典项都需要一个键和值,因此假设字典的完整结构如下所示:
sample_dict = {'NorthernRegion': {'date': '2021-12-31',
'state': 'PA',
'candySales': 500,
'grocerySales': 1500,
'electronicSales': 800},
'SouthernRegion':{'date': '2021-12-31',
'state': 'PA',
'candySales': 500,
'grocerySales': 1500,
'electronicSales': 800}}
To get the inner dictionaries as columns as the outer keys as index values, you can try pd.DataFrame(sample_dict).T
which will result in the following DataFrame:要将内部字典作为列作为外部键作为索引值,您可以尝试pd.DataFrame(sample_dict).T
这将导致以下 DataFrame:
date state candySales grocerySales electronicSales
NorthernRegion 2021-12-31 PA 500 1500 800
SouthernRegion 2021-12-31 PA 500 1500 800
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.