valueerror: if using all scalar values, must pass index – Code Example

Total
0
Shares

In this article I will provide you multiple code examples to resolve Python valueerror: if using all scalar values, you must pass an index. Dataframes in Python Pandas throw this error when we provide scalar values in dictionary but without any index.

Code Examples

Error Code – Replicating valueerror: if using all scalar values, you must pass an index –

df = pd.DataFrame({'A':1,'B':2})

Output –

Traceback (most recent call last):
  File "jdoodle.py", line 3, in <module>
    df = pd.DataFrame({'A':1,'B':2})
  File "/usr/lib/python3.6/site-packages/pandas/core/frame.py", line 348, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/usr/lib/python3.6/site-packages/pandas/core/frame.py", line 459, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/usr/lib/python3.6/site-packages/pandas/core/frame.py", line 7315, in _arrays_to_mgr
    index = extract_index(arrays)
  File "/usr/lib/python3.6/site-packages/pandas/core/frame.py", line 7352, in extract_index
    raise ValueError('If using all scalar values, you must pass'
ValueError: If using all scalar values, you must pass an index

Solutions

Method 1 – Don’t use scalar, use list –

df = pd.DataFrame({'A': [1], 'B': [2]})

Method 2 – Pass index –

df = pd.DataFrame({'A': 1, 'B': 2}, index=[0])

Method 3 – Wrap dictionary into list –

my_dict = {'A':1,'B':2}
df = pd.DataFrame([my_dict])

Method 4 – Using from_records() method –

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

You may provide index too –

df = pd.DataFrame.from_records([{ 'A':1,'B':2 }], index='A')

Method 5 – Using Pandas Series –

df = pd.Series({'A': 1, 'B': 2}).to_frame()

You may provide column in to_frame() function –

df = pd.Series({'A': 1, 'B': 2}).to_frame('A')

Method 6 – Using orient=index

df = pd.DataFrame.from_dict({'A':1,'B':2}, orient = 'index')

Method 7 – Separate out keys and values in dictionary –

df = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})

Method 8 – Convert dictionary to list using list() and .items()

df = pd.DataFrame(list({'A': 1, 'B': 2}.items()))

Live Demo

Open Live Demo