问题描述
我是python的新手,在以键和值的格式(即
I am new to python and i am facing problem in creating the Dataframe in the format of key and value i.e.
data = [{'key':'\[GlobalProgramSizeInThousands\]','value':'1000'},]
这是我的代码
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);
但是当我在DataFrame中传递数据时,它显示了我 pandas.core.common.PandasError:DataFrame构造函数未正确调用!.
But when i pass the data in DataFrame it shows me pandas.core.common.PandasError: DataFrame constructor not properly called!.
如果我打印数据并将相同的值分配给data变量,那么它将起作用.
while if i print the data and assign the same value to data variable then it works.
推荐答案
您要向DataFrame构造函数提供字典的字符串表示形式,而不是字典本身.因此,这就是您收到该错误的原因.
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
因此,如果您想使用代码,则可以执行以下操作:
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"]})
但是也许甚至不需要这样做,因为根据您result_set
中的确切内容,您可能会:
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
- 直接将其提供给DataFrame:
DataFrame(result_set)
- 或使用熊猫
read_sql_query
函数为您执行此操作(请参见文档)
- provide this directly to a DataFrame:
DataFrame(result_set)
- or use the pandas
read_sql_query
function to do this for you (see docs on this)
这篇关于DataFrame构造函数未正确调用!错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!