how to convert dataframe to dict code example

Example 1: convert dict to dataframe

#Lazy way to convert json dict to df

pd.DataFrame.from_dict(data, orient='index').T

Example 2: dataframe to dictionary

>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]

Example 3: convert pandas dataframe to dict with a column as key

df.set_index('columnName').T.to_dict()

Example 4: dataframe to dict without index

{'Name': ['John', 'Sara', 'John', 'Sara'],
 'Sem': ['Sem1', 'Sem1', 'Sem2', 'Sem2'],
 'Subject': ['Mathematics', 'Biology', 'Biology', 'Mathematics'],
 'Grade': ['A', 'B', 'A+', 'B++']}

Tags:

Java Example