user9639519
user9639519

Reputation:

PandasError: DataFrame constructor not properly called

I am trying to convert some values to a dataframe. I have used the following code to achieve this:

import pandas as pd
import numpy as np

k = 5
N = 8

d = ({'Time' : np.random.randint(k, k + 100 , size=N),
    'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'],
    'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'],
    'Number2' : [1,1,'xx',1,'xx',2,'xx',2]}),

df = pd.DataFrame(data=d)

However, this produces an error code PandasError: DataFrame constructor not properly called!.

I have tried to alter the code to df = pd.DataFrame(eval(d)) but get the same error?

Any suggestions?

Upvotes: 1

Views: 13927

Answers (2)

sacuL
sacuL

Reputation: 51335

As you have it, d is a tuple:

>>> type(d)
<class 'tuple'>

But the first element is a dict:

>>> type(d[0])
<class 'dict'>

so you can do:

pd.DataFrame(data=d[0])

Which returns:

  Events Number1 Number2  Time
0    ABC      xx       1    77
1    DEF      xx       1    39
2    GHI       1      xx    15
3    JKL      xx       1    21
4    ABC      xx      xx    21
5    DEF      xx       2    64
6    GHI       2      xx    84
7    JKL      xx       2    60

Upvotes: 1

BENY
BENY

Reputation: 323226

You have a typo

d = ({'Time' : np.random.randint(k, k + 100 , size=N),
    'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'],
    'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'],
    'Number2' : [1,1,'xx',1,'xx',2,'xx',2]})# used to have comma here
df = pd.DataFrame(data=d)

Upvotes: 4

Related Questions