I intend to get a dictionary with column name as key from a dataframe.
Suppose I have a dataframe:
a b
0 ac dc
1 ddd fdf
I want the output as:
{a : ac, b : dc}
I want it to be done row by row. Any sort of help would be greatly appreciated. Here I want the column name as the key in the resulting dictionary.
To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.
You can use df. to_dict() in order to convert the DataFrame to a dictionary.
To create a dictionary from two column values, we first create a Pandas series with the column for keys as index and the other column as values. And then we can apply Pandas' to_dict() function to get dictionary.
to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter. Parameters: orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).
You can use the to_dict()
method with orient='records'
import pandas as pd
df = pd.DataFrame([{'a': 'ac', 'b': 'dc'}, {'a': 'ddd', 'b': 'fdf'}])
print(df)
# a b
# 0 ac dc
# 1 ddd fdf
d = df.to_dict(orient='records')
print(d)
# [{'b': 'dc', 'a': 'ac'}, {'b': 'fdf', 'a': 'ddd'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With