Python 未正确调用 DataFrame 构造函数!错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25604115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataFrame constructor not properly called! error
提问by Ravi khatri
I am new to python and i am facing problem in creating the Dataframe in the format of key and value i.e.
我是 python 的新手,我在以键和值的格式创建数据帧时遇到问题,即
data = [{'key':'\[GlobalProgramSizeInThousands\]','value':'1000'},]
Here is my My code
这是我的代码
columnsss = ['key','value'];
query = "select * from bparst_tags where tag_type = 1 ";
result = database.cursor(db.cursors.DictCursor);
result.execute(query);
result_set = result.fetchall();
data = "[";
for row in result_set:
`row["tag_expression"]`)
data += "{'value': %s , 'key': %s }," % ( `row["tag_expression"]`, `row["tag_name"]` )
data += "]" ;
df = DataFrame(data , columns=columnsss);
But when i pass the data in DataFrame it shows me pandas.core.common.PandasError: DataFrame constructor not properly called!.
但是当我在 DataFrame 中传递数据时,它显示我pandas.core.common.PandasError: DataFrame 构造函数没有正确调用!.
while if i print the data and assign the same value to data variable then it works.
而如果我打印数据并将相同的值分配给数据变量,那么它就可以工作。
采纳答案by joris
You are providing a stringrepresentation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
您正在向DataFrame 构造函数提供dict的字符串表示形式,而不是 dict 本身。所以这就是你得到那个错误的原因。
So if you want to use your code, you could do:
所以如果你想使用你的代码,你可以这样做:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
但是最好不要首先创建字符串,而是直接将其放入字典中。大致如下:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_setyou could probably:
但可能甚至不需要这样做,因为根据您的确切内容,您result_set可能会:
- provide this directly to a DataFrame:
DataFrame(result_set) - or use the pandas
read_sql_queryfunction to do this for you (see docson this)
- 将其直接提供给 DataFrame:
DataFrame(result_set) - 或使用 pandas
read_sql_query函数为您执行此操作(请参阅有关此的文档)

