Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dataframe to dictionary [duplicate]

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.

like image 848
Sunil Kumar Avatar asked Dec 17 '15 07:12

Sunil Kumar


People also ask

How do you convert a DataFrame to a 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.

How do you create a dictionary from a DataFrame column?

You can use df. to_dict() in order to convert the DataFrame to a dictionary.

How do I convert a two column DataFrame to a dictionary in pandas?

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.

What does To_dict do in Python?

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).


1 Answers

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'}]
like image 97
mirosval Avatar answered Oct 10 '22 20:10

mirosval