Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas.DataFrame to list of dictionaries in Python

I have a dictionary which is converted from a dataframe as below :

a = d.to_json(orient='index')

Dictionary :

{"0":{"yr":2017,"PKID":"58306, 57011","Subject":"ABC","ID":"T001"},"1":{"yr":2018,"PKID":"1234,54321","Subject":"XYZ","ID":"T002"}}

What I need is it be in a list, so essentially a list of dictionary. So i just add a [] because that is the format to be used in the rest of the code.

input_dict = [a]

input_dict :

['
{"0":{"yr":2017,"PKID":"58306, 57011","Subject":"ABC","ID":"T001"},"1":{"yr":2018,"PKID":"1234,54321","Subject":"XYZ","ID":"T002"}}
']

I need to get the single quotes removed just after the [ and just before the ]. Also, have the PKID values in form of list.

How can this be achieved ?

Expected Output :

[ {"yr":2017,"PKID":[58306, 57011],"Subject":"ABC","ID":"T001"},"1":{"yr":2018,"PKID":[1234,54321],"Subject":"XYZ","ID":"T002"} ]

NOTE : The PKID column has multiple integer values which have to come as a lift of integers. a string is not acceptable. so we need like "PKID":[58306, 57011] and not "PKID":"[58306, 57011]"

like image 732
Shankar Pandey Avatar asked Feb 28 '18 10:02

Shankar Pandey


People also ask

How do I convert a pandas 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 convert a DataFrame to a list in Python?

To convert Pandas DataFrame to List in Python, use the DataFrame. values(). tolist() function.

When we create DataFrame from list of dictionaries to dictionary keys will become?

Example 1: As we know while creating a data frame from the dictionary, the keys will be the columns in the resulted Dataframe. When we create Dataframe from a list of dictionaries, matching keys will be the columns and corresponding values will be the rows of the Dataframe.

What is Tolist () in pandas?

Pandas series can be converted to a list using tolist() or type casting method. There can be situations when you want to perform operations on a list instead of a pandas object. In such cases, you can store the DataFrame columns in a list and perform the required operations.


1 Answers

pandas.DataFrame.to_json returns a string (JSON string), not a dictionary. Try to_dict instead:

>>> df
   col1  col2
0     1     3
1     2     4
>>> [df.to_dict(orient='index')]
[{0: {'col1': 1, 'col2': 3}, 1: {'col1': 2, 'col2': 4}}]
>>> df.to_dict(orient='records')
[{'col1': 1, 'col2': 3}, {'col1': 2, 'col2': 4}]
like image 196
Norrius Avatar answered Oct 13 '22 13:10

Norrius