python
Pandas dataframe to dictionary conversion python
Pandas Dataframe provides multiple methods to convert Dataframe to python dictionary. We are listing them one by one with descriptions.
import pandas as pd
data = {
'name': ['Rick', 'Carol', 'Carl', 'Negan'],
'place': ['Alexendria', 'Kingdom', 'Alexendria', 'Saviours']
}
df = pd.DataFrame.from_dict(data)
print(df)
# name place
# 0 Rick Alexendria
# 1 Carol Kingdom
# 2 Carl Alexendria
# 3 Negan Saviours
# Get dict from dataframe(Method 1)
dict1 = dict(df.values)
print(dict1)
# -> {'Rick': 'Alexendria', 'Carol': 'Kingdom', 'Carl': 'Alexendria', 'Negan': 'Saviours'}
# Get dict from dataframe(Method 2)
dict2 = df.to_dict('index')
print(dict2)
# -> {0: {'name': 'Rick', 'place': 'Alexendria'}, 1: {'name': 'Carol', 'place': 'Kingdom'}, 2: {'name': 'Carl', 'place': 'Alexendria'}, 3: {'name': 'Negan', 'place': 'Saviours'}}
Was this helpful?
Similar Posts
- Convert pandas DataFrame to python collection - dictionary
- Convert a dictionary to pandas DataFrame in python
- Convert a Python Dictionary to Pandas DataFrame
- String to date conversion using Pandas
- Pandas - How to check whether a pandas DataFrame is empty
- Pandas - Delete,Remove,Drop, column from pandas DataFrame
- Integer to String conversion in Python