【问题标题】:JSON inside column DataFrame列 DataFrame 内的 JSON
【发布时间】:2021-05-20 12:50:15
【问题描述】:

我正在尝试对数据框进行批量插入,我在 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] }

【问题讨论】:

  • 试过json.dumps(your_data) 吗? { 'age_max': 44, 'age_min': [20,30] } 似乎是 python dictjson.dumps({ 'age_max': 44, 'age_min': [20,30] }) 会给你 JSON 字符串 '{ "age_max": 44, "age_min": [20,30] } '
  • 如果您使用 JSON,为什么要使用 Dataframe?您还有其他包含表格数据的列吗?
  • @el_oso 我有表格数据,在我有 JSON 的列内,如何将它插入 Postgres?在 postgres 中,我也有一个 JSON 类型的列。

标签: python sql json pandas postgresql


【解决方案1】:

pandas 已自动将 json 转换为字典对象。您可以使用内置json 模块中的dumps 轻松地将字典转换为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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 2018-06-09
    • 1970-01-01
    • 2020-04-14
    • 2023-03-13
    • 2021-03-27
    • 2015-09-16
    • 2019-05-25
    相关资源
    最近更新 更多