python 如何将dataframe数据批量插入到clickhouse

1. 背景-问题描述

最近做一个资产数据清洗工作,结束后需要将数据批量插入到clickhouse;查找并尝试了好几种批量插入的方式均已失败告终;现就查到的dataframe类型数据批量插入到clickhouse记录和汇总于此。

2. 配置信息

python 3.12
clickhouse_driver 0.2.9
PyYAML 6.0.2
pandas 2.2.3
numpy 2.1.2

3. 单条数据插入

from clickhouse_driver import Client
client = Client(
	host='host',
  	port='port',
  	user='user',
  	password='password',
  	settings={
   'use_numpy': True}
)
# 创建表格
client.execute("CREATE TABLE IF NOT EXISTS db.test_table (id Int32, name String) ENGINE = MergeTree")
sql = "INSERT INTO db.test_table (id, name) VALUES (1, 'test_1')"
client.execute(sql)

db.test_table: db表示数据库,test_table表示表名称

4. 多条数据插入

# 多条数据插入
sql = "INSERT INTO db.test_table (id, name) VALUES (1, 'test_1'), (2, 'test_2')"
client.execute(sql)

5. dataframe数据全部插入

5.1 将需要插入的数据写入到sql中

# 取出dataframe列
import pandas as pd
import numpy as np
from clickhouse_driver import Client

client = Client(
	host='host',
  	port='port',
  	user='user',
  	password='password',
 	settings={
   'use_numpy': True}
)

# 创建一个示例DataFrame
data = {
   
    'id': [1, 2, 3],
    'name': ['name_1', 'name_2', 'name_3']
}
df = pd.DataFrame(data)
cols = df.columns.tolist()
sql0 = f"INSERT INTO db.test_table ({
     ','.join(map(str, cols))}) VALUES"
# 将df下的values转化为tuple格式: [(1, 'name_1'), (2, 'name_2'),(3, 'name_3')]
tuples = [tuple(x) for x in df.to_numpy()]
sql = f"{
     sql0}" + ', '.join(map(str, tuples))
client.execute(sql)

5.2 使用insert_dataframe

cols = df.columns.tolist()
query = f"INSERT INTO {
     table
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值