2015-09-04 125 views
2

我在这里有一个棘手的问题,关于将JSON字符串转换为Python数据字典用于分析Pandas。我已阅读了其他一些问题,但没有一个对我的案例起作用。将JSON转换为Python Dict与SQLAlchemy导入的Postgresql数据

以前,我只是简单地使用CSV(和Pandas的read_csv函数)来执行我的分析,但现在我已经开始直接从PostgreSQL中提取数据。

我没有问题,使用SQLAlchemy连接到我的引擎并运行我的查询。我的整个脚本与我从CSV中获取数据时的运行方式相同。也就是说,直到它转到我试图将其中一列(即下面的示例文本中的'config'列)从JSON转换为Python字典的部分。将其转换为字典的最终目标是能够计算“config”列中“选项”字段下的响应数量。

df = pd.read_sql_query('SELECT questions.id, config from questions ', engine) 

df = df['config'].apply(json.loads) 

df = pd.DataFrame(df.tolist()) 

df['num_options'] = np.array([len(row) for row in df.options]) 

当我运行这个,我得到错误“TypeError:预期的字符串或缓冲区”。我尝试将'config'列中的数据转换为来自对象的字符串,但这并没有做到这一点(我得到了另一个错误,例如“ValueError:Expecting property name ...”)。

如果有帮助,这里有一个在“配置”柱剪断数据从一个细胞(代码应返回的结果“6”这个剪断,因为有6个选项):

{"graph_by":"series","options":["Strongbow Case Card/Price Card","Strongbow Case Stacker","Strongbow Pole Topper","Strongbow Base wrap","Other Strongbow POS","None"]} 

我猜测是SQLAlchemy在将数据从数据库中提取出来时会对JSON字符串做些奇怪的事情?当我只是从数据库中提取CSV时不会发生什么?

回答

0

在最近的Psycopg版本中,Postgresql json(b)适配Python是透明的。 Psycopg是默认的SQLAlchemy驱动PostgreSQL的

df = df['config']['options'] 

Psycopg手册:

Psycopg can adapt Python objects to and from the PostgreSQL json and jsonb types. With PostgreSQL 9.2 and following versions adaptation is available out-of-the-box. To use JSON data with previous database versions (either with the 9.1 json extension, but even if you want to convert text fields to JSON) you can use the register_json() function.

+0

对不起,我在回复您的延迟,但这种完美工作,非常感谢分享! –

0

只是sqlalchemy查询:

q = session.query(
    Question.id, 
    func.jsonb_array_length(Question.config["options"]).label("len") 
) 

sql和熊猫read_sql_query

sql = """\ 
SELECT questions.id, 
     jsonb_array_length(questions.config -> 'options') as len 
FROM questions 
""" 
df = pd.read_sql_query(sql, engine) 

合并两组(我的最爱):

# take `q` from the above 
df = pd.read_sql(q.statement, q.session.bind)