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

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


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  B0  2  3

or use scalar values and pass an index:

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


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')


You need to create a pandas series first. The second step is to convert the pandas series to pandas dataframe.

import pandas as pddata = {'a': 1, 'b': 2}pd.Series(data).to_frame()

You can even provide a column name.

pd.Series(data).to_frame('ColumnName')


matomo