Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dict of scalars to pandas DataFrame [duplicate]

Under Python3, I have a dict with the following format:

my_dict = {'col1': 1.0, 'col2':2.0, 'col3': 3.0}

And I want to convert it to a pandas DataFrame using dict keys as columns:

      col1  col2  col3
0     1.0   2.0   3.0

However, when I try the following command I have a ValueError:

df = pd.DataFrame(my_dict)

ValueError: If using all scalar values, you must pass an index
like image 969
Pierre S. Avatar asked Jan 25 '19 12:01

Pierre S.


People also ask

How do I convert a dictionary to a DataFrame pandas?

You can convert a dictionary to Pandas Dataframe using df = pd. DataFrame. from_dict(my_dict) statement.

How do you create a DataFrame from a dictionary?

Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.

What is a correct syntax to load a Python dictionary called data into a pandas DataFrame?

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.

Is dict faster than DataFrame?

For certain small, targeted purposes, a dict may be faster. And if that is all you need, then use a dict, for sure! But if you need/want the power and luxury of a DataFrame, then a dict is no substitute.


1 Answers

Use:

df = pd.DataFrame([my_dict])

Or:

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

Or:

df = pd.DataFrame(my_dict, index=[0])

print (df)
   col1  col2  col3
0   1.0   2.0   3.0
like image 96
jezrael Avatar answered Sep 28 '22 22:09

jezrael