Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

This may be a simple question, but I can not figure out how to do this. Lets say that I have two variables as follows.

a = 2 b = 3 

I want to construct a DataFrame from this:

df2 = pd.DataFrame({'A':a,'B':b}) 

This generates an error:

ValueError: If using all scalar values, you must pass an index

I tried this also:

df2 = (pd.DataFrame({'a':a,'b':b})).reset_index() 

This gives the same error message.

like image 219
Nilani Algiriyage Avatar asked Jul 24 '13 16:07

Nilani Algiriyage


People also ask

What is ValueError in Python pandas?

One of the most commonly reported error in pandas is ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() and it may sometimes be quite tricky to deal with, especially if you are new to pandas library (or even Python).

What does .values do in pandas?

The values property is used to get a Numpy representation of the DataFrame. Only the values in the DataFrame will be returned, the axes labels will be removed. The values of the DataFrame. A DataFrame where all columns are the same type (e.g., int64) results in an array of the same type.


2 Answers

The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:

>>> df = pd.DataFrame({'A': [a], 'B': [b]}) >>> df    A  B 0  2  3 

or use scalar values and pass an index:

>>> df = pd.DataFrame({'A': a, 'B': b}, index=[0]) >>> df    A  B 0  2  3 
like image 92
DSM Avatar answered Oct 01 '22 15:10

DSM


You can also use pd.DataFrame.from_records which is more convenient when you already have the dictionary in hand:

df = pd.DataFrame.from_records([{ 'A':a,'B':b }]) 

You can also set index, if you want, by:

df = pd.DataFrame.from_records([{ 'A':a,'B':b }], index='A') 
like image 25
fAX Avatar answered Oct 01 '22 16:10

fAX