This article will guide you through the process of converting a Pandas DataFrame to a dictionary with clear examples.
Sample dataframe:
import pandas as pd
# Sample data: Age and Score for Sachin, Ram, Abhilash, Mike, and Elaine
df = pd.DataFrame({
'Age': [25, 30, 29, 24, 27],
'Score': [85, 88, 76, 90, 82]
}, index=['Sachin', 'Ram', 'Abhilash', 'Mike', 'Elaine'])
print(df)
Converting DataFrame to Dictionary:
Using to_dict()
Method:
Pandas provides a to_dict()
method that can transform a DataFrame into a dictionary. By default, it uses a column-wise orientation.
default_dict = df.to_dict()
print(default_dict)
Output:
{
'Age': {
'Sachin': 25,
'Ram': 30,
'Abhilash': 29,
'Mike': 24,
'Elaine': 27
},
'Score': {
'Sachin': 85,
'Ram': 88,
'Abhilash': 76,
'Mike': 90,
'Elaine': 82
}
}
Row-wise Conversion:
If you want to convert your DataFrame into a dictionary with row-wise orientation, you can set the orient parameter to ‘index’.
row_dict = df.to_dict(orient='index')
print(row_dict)
Output:
{
'Sachin': {'Age': 25, 'Score': 85},
'Ram': {'Age': 30, 'Score': 88},
'Abhilash': {'Age': 29, 'Score': 76},
'Mike': {'Age': 24, 'Score': 90},
'Elaine': {'Age': 27, 'Score': 82}
}
Refer more on python here : Python
Refer more on Pandas here
Refer more on python here : PySpark