首页 > 解决方案 > 列 DataFrame 内的 JSON

问题描述

我正在尝试批量插入数据框,我在 Postgres 中的表有一个字段类型JSON,我想在其上插入原始 JSON,但是当我尝试制作它时,python 从双引号变为"单引号引用',它在技术上破坏了我在 DataFrame 中的 JSON 列,我正在寻找一种方法来进行批量插入。

首先,我以 json 格式获取数据,接下来我制作了一个用于数据操作和清理的 Dataframe,最后我想在 Postgres 中插入批量这个 DF。

df = pd.DataFrame(response['data'])

这就是 python 如何将我的 JSON 从转换 { "age_max": 44, "age_min": [20,30] } 为: { 'age_max': 44, 'age_min': [20,30] }

标签: pythonsqljsonpandaspostgresql

解决方案


pandas 已自动将 json 转换为字典对象。dumps您可以使用内置json模块轻松地将字典转换为 json 。

import requests
from json import dumps

import pandas
import psycopg2

#sample dataset 
df = pandas.DataFrame.from_dict(
{'date': {0: '2021-02-16',
  1: '2021-02-15',
  2: '2021-02-14',
  3: '2021-02-13',
  4: '2021-02-12'},
 'name': {0: 'East Midlands',
  1: 'East Midlands',
  2: 'East Midlands',
  3: 'East Midlands',
  4: 'East Midlands'},
 'cases': {0: {'new': 174, 'cumulative': 294582},
  1: {'new': 1477, 'cumulative': 294408},
  2: {'new': 899, 'cumulative': 292931},
  3: {'new': 898, 'cumulative': 292032},
  4: {'new': 1268, 'cumulative': 291134}}}
)

df['json'] = df['cases'].apply(dumps) #create new series running the function json.dumps against each element in the series
p = df[['date', 'name', 'json']].values.tolist() #create parameter list

con = db_connection() #replace with your db connection function or  psycopg2.connect()

csr = con.cursor()
sql = """insert into corona (date, name, json) values (%s, %s, %s)"""
csr.executemany(sql, params=p)
con.commit()
con.close()

推荐阅读