PandasError: DataFrame constructor not properly called! – Code Example

Total
0
Shares

In this article we will see the Python Pandas code to resolve pandas.core.common.PandasError: DataFrame constructor not properly called! According to this error Pandas is trying to say that the data passed to the DataFrame constructor is invalid.

According to Pandas documentation, DataFrame constructor looks like this –

class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)

The first argument is data. The valid data values are –

  • ndarray (structured or homogeneous),
  • Iterable,
  • dict,
    • Series,
    • arrays,
    • constants,
    • dataclass
    • list-like objects
  • DataFrame

Anything apart from the valid data values will throw pandas.core.common.PandasError: DataFrame constructor not properly called!

Code Example

Error Code – Let’s first replicate the error –

import pandas as pd

d = "{'col1': [1, 2], 'col2': [3, 4]}"
df = pd.DataFrame(data=d)
print(df)

This code will throw the error –

Traceback (most recent call last):
  File "dataframe.py", line 4, in <module>;
    df = pd.DataFrame(data=d)
  File "/usr/lib/python3.6/site-packages/pandas/core/frame.py", line 422, in __init__
    raise ValueError('DataFrame constructor not properly called!')
ValueError: DataFrame constructor not properly called!

It’s because we passed string as data to the dataframe. String is not a valid datatype for dataframe.

Solution

Here is the correct code –

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
print(df)

The output will be –

   col1  col2
0     1     3
1     2     4

Live Demo

Open Live Demo