How to Fix: if using all scalar values, you must pass an index

This tutorial shows how to fix the error when using Pandas.

if using all scalar values, you must pass an index

You encounter this error because you are trying to create a dataframe with all scalar values, but without adding index at the same time.

Reproduces the Error

# import pandas 
import pandas as pd

# create a DataFrame with scalar values
df = pd.DataFrame({'X': 2, 'Y': 4, 'Z': 7})

Output:

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

Two Methods to Fix the Error

Method 1: Fixing the error by converting the scalars as lists

# import pandas 
import pandas as pd

# create a DataFrame with lists
df = pd.DataFrame({'X': [2], 'Y': [4], 'Z': [7]})

# print out the df
print(df)

Output:

   X  Y  Z
0  2  4  7

Method 2: Manually add an index for it

You can add an index number in the code.

# import pandas 
import pandas as pd

# create a DataFrame with lists
df = pd.DataFrame({'X': 2, 'Y': 4, 'Z': 7}, index=[0])

# print out the df
print(df)

Output:

   X  Y  Z
0  2  4  7

Note that, you can use a number other than 0. For instance, you can set the index number as 2 as well.

# import pandas 
import pandas as pd

# create a DataFrame with lists
df = pd.DataFrame({'X': 2, 'Y': 4, 'Z': 7}, index=[2])

# print out the df
print(df)

Output:

   X  Y  Z
2  2  4  7

Further Reading