python - 列 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] }
解决方案
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()
推荐阅读
- javascript - 如何通过在文本输入上按 Enter 来触发功能(React)
- css - Flex 和加载懒惰
- azure - 无法在 Azure 中使用 Python SDK 获取虚拟机规模集的公共 IP 地址
- android - 有没有办法实现一个Android报警应用程序?
- python - 从浏览器获取视频流到opencv?
- sql - 在类型转换中需要有关 SQL Server 中执行计划的帮助
- reactjs - React 中的 SSR 缓存?
- django - 带有清晰表单的内联表单集 - 仅显示一次标签
- node.js - Google 表格 v4 API 为不包含任何元素的行返回空数组
- android - MIPI显示检测