Register Login

ValueError if using all scalar values, you must pass an index

Updated Jan 15, 2020

The most common ways of creating data frames in Python are using lists and dictionaries. You can use a list of lists or a dictionary of lists. While creating data frames you might encounter an error Valueerror if using all scalar values, you must pass an index.” We will look at the reason behind the occurrence of this error and the ways to solve it.

The code is as follows:

# Import pandas module
import pandas as pds

# Create dictionary data type
dict_fruit = {
'Apple':'Red',
'Mango':'Green',
'Orange':'Orange'
}

# convert dictionary to a data frame
data_frame = pds.DataFrame.from_dict(dict_fruit)
print(data_frame)

Output:

raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index

This error occurs as Pandas is expecting the data values to be list values or dict values. According to the code mentioned above, you are passing a scalar value. In that case, you also have to pass in the index.

ValueError if using all scalar values, you must pass an index

How to solve ValueError: if using all scalar values, you must pass an index?

So in order to avoid this error, you have to modify the code and provide index values to Pandas while creating a data frame. Here is how you can fix it:

Change the dictionary data and pass index

# Import pandas module
import pandas as pds

# Create a dictionary data type
dict_fruit = {
'Apple':['Red'],
'Mango':['Green'],
'Orange':['Orange']
}

# convert dictionary to a data frame
data_frame = pds.DataFrame.from_dict(dict_fruit)
print(data_frame)

Output:

Apple  Mango  Orange
0   Red  Green  Orange

Now, let us look at another example of creating a data frame. Suppose you have two variables from which you want to create a data frame.

The values are:

A=2
b=3

When you write the code to construct a DataFrame like this:

# Import pandas module
import pandas as pds

# convert dictionary to a data frame
data_frame = pds.DataFrame({'A':2,'B':3})
print(data_frame)

Output:

raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index

Here is the solution:

In this case, you can either use non-scalar values for the columns. Instead, you can use a list like this,

Correct Code:

# Import pandas module
import pandas as pds

# convert dictionary to a data frame
data_frame = pds.DataFrame({'A':[2],'B':[3]})
print(data_frame)

Output:

A  B
0  2  3

Alternatively, you can pass in scalar values along with index values with them,

# Import pandas module
import pandas as pds

# convert dictionary to a data frame
data_frame = pds.DataFrame({'A':2,'B':3}, index=[0])
print(data_frame)

Output:

A  B
0  2  3

Thus, value errors like the one mentioned above can be avoided by providing proper index values.


×