Chrome Extension

Convert pandas DataFrame to python collection - dictionary

You can convert pandas data frame to python dictionary using to_dict() method. There are many parameters you can pass to this method to get the desired format of the dictionary.
import pandas as pd

df = pd.DataFrame()
df["Name"] = ["John", "Mark", "Rick"]
df["Score"] = [20, 50, 70]

print(df.to_dict())
# prints - {'Name': {0: 'John', 1: 'Mark', 2: 'Rick'}, 'Score': {0: 20, 1: 50, 2: 70}}

print(df.to_dict('split'))
# prints - {'index': [0, 1, 2], 'columns': ['Name', 'Score'], 'data': [['John', 20], ['Mark', 50], ['Rick', 70]]}

print(df.to_dict('records'))
# prints - [{'Name': 'John', 'Score': 20}, {'Name': 'Mark', 'Score': 50}, {'Name': 'Rick', 'Score': 70}]

print(df.to_dict('index'))
#prints - {0: {'Name': 'John', 'Score': 20}, 1: {'Name': 'Mark', 'Score': 50}, 2: {'Name': 'Rick', 'Score': 70}}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Search Index Data (The code snippet can also be found with below search text)

data frame to dict pandas
Was this helpful?
0 Comments
Join Devsheet Ask a Question