How to convert dictionary to pandas dataframe

I am trying to convert a dictionary that has only 1 entry in a pandas dataframe. I used the following code from other solutions:

d = {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'} pd.DataFrame(d.items(), columns=['id', 'cost','name']) 

But I get the following error:

 PandasError: DataFrame constructor not properly called! 
+6
source share
3 answers

You have only one list of entries:

 import pandas as pd d = {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'} df = pd.DataFrame([d], columns=d.keys()) print df 

Output:

  id cost name 0 CS2_056 2 Tap 
+16
source

Although this question has a duplicate ( Python Dictionary for Pandas Dataframe ), I find that there is a simpler answer than the ones provided there.

Convert values ​​to lists:

d = {'id': ['CS2_056'], 'cost': [2], 'name': ['Tap']}

then just:

 df = pd.DataFrame(d) print(df) # cost id name # 0 2 CS2_056 Tap 


Keep in mind that if the value of the columns is set, you still need to explicitly point the columns to the DataFrame :

 df = pd.DataFrame(d, columns=['id', 'cost', 'name']) print(df) # id cost name # 0 CS2_056 2 Tap 
0
source

Maybe you are using python3. in python3 we have a list there

 pd.DataFrame(list(d.items()), columns=['id', 'cost','name']) 
0
source

Source: https://habr.com/ru/post/1015290/


All Articles