Create Dictionary from pandas DataFrame in Python (Example Code)
In this post, I’ll demonstrate how to transform a pandas DataFrame to a dictionary in Python.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A': ['xxx'], # Constructing a pandas DataFrame 'B': ['yyy'], 'C': ['zzz']}) print(my_df) # A B C # 0 xxx yyy zzz |
my_df = pd.DataFrame({'A': ['xxx'], # Constructing a pandas DataFrame 'B': ['yyy'], 'C': ['zzz']}) print(my_df) # A B C # 0 xxx yyy zzz
Example: Applying to_dict() Function to Convert pandas DataFrame to Dictionary
df_to_dict = my_df.to_dict() # Using to_dict print(df_to_dict) # {'A': {0: 'xxx'}, 'B': {0: 'yyy'}, 'C': {0: 'zzz'}} |
df_to_dict = my_df.to_dict() # Using to_dict print(df_to_dict) # {'A': {0: 'xxx'}, 'B': {0: 'yyy'}, 'C': {0: 'zzz'}}
Related Articles & Further Resources
You may have a look at the following Python programming language tutorials. They illustrate topics such as data conversion and lists.