![]() |
In this article, we will learn how to convert Pandas DataFrame to Nested Dictionary. Convert Pandas Dataframe To Nested DictionaryConverting a Pandas DataFrame to a nested dictionary involves organizing the data in a hierarchical structure based on specific columns. In Python’s Pandas library, we can utilize the groupby function along with apply to create groupings based on chosen columns. Let’s create a DataFrame that contains information about different products, including their names, prices, and stock quantities. The to_dict method with the parameter orient=records is commonly employed to convert each group into a dictionary of records. Let’s see how to convert dataframe to nested dictionary: Using to_dictPython3
Output: {'David': [{'Chain': 'Starbucks', 'Food': 'coffee', 'Healthy': False}, Let’s see another complex example, to gain in-depth understanding. Python3
Output: {('Alice', 'Home'): [{'Activity': 'Cooking', 'Duration': 30}, {'Activity': 'Reading', 'Duration': 45}], ConclusionHence, we can convert Pandas Dataframe To Nested Dictionary with just few lines of code. |
Reffered: https://www.geeksforgeeks.org
Pandas |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |