简体   繁体   English

PandasError:DataFrame构造函数未正确调用

[英]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! 但是,这会产生错误代码PandasError: DataFrame constructor not properly called! .

I have tried to alter the code to df = pd.DataFrame(eval(d)) but get the same error? 我试图将代码更改为df = pd.DataFrame(eval(d))但得到相同的错误?

Any suggestions? 有什么建议么?

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)

As you have it, d is a tuple: 有了它, d是一个元组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM