pandas使用to_sql写入SQL报错参数不支持及设置时间索引问题
问题解答
1 修复参数绑定报错
报错的根本原因是你对a列的字符串转换操作没有实际生效:你的a列存储的是嵌套列表/NumPy数组,直接调用astype('str')无法将整个嵌套结构转为标准字符串类型,写入SQL时数据库无法识别列表/数组类型,就会触发参数绑定错误。
正确的处理逻辑是将数组序列化为可无损还原的字符串格式,推荐用JSON序列化方案,实现简单且兼容性好:
- 写入前:将数组转为嵌套列表后用
json.dumps转成标准字符串 - 读取后:用
json.loads解析字符串为列表,再转回NumPy数组即可还原原格式
修正后的转换代码如下:
import json # 将a列序列化字符串 testdata['a'] = testdata['a'].apply(lambda x: json.dumps(np.array(x).tolist())) # 读取时还原数组 # df['a'] = df['a'].apply(lambda x: np.array(json.loads(x)))
2 修复索引设置不生效问题
pandas的set_index方法默认不会修改原对象,只会返回设置好索引的新DataFrame,你之前只调用了testframe.set_index('time')没有赋值或者开启inplace参数,所以原DataFrame的索引没有变化。
两种正确写法二选一即可:
写法1:覆盖原对象
testframe = testframe.set_index('time')
写法2:开启原地修改参数
testframe.set_index('time', inplace=True)
完整可运行修正代码
import pandas as pd import sqlite3 import numpy as np import json from datetime import datetime # 初始化数据库连接 conn = sqlite3.connect('test_database.db') # 构造测试数据 time_val = datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S') testdata = {'time': time_val , 'a': [[[-1.13855, -1.13855, -1.2212, -1.27331, -1.32733, -1.39211, -1.46947, -1.55818, -1.65584, -1.75972, -1.86731, -1.97665, -2.08624, -2.19495, -2.30196, -2.40665, -2.50857, -2.60744, -2.70314, -2.79567, -2.885, -2.97102, -3.05448, -3.13868, -3.22736, -3.31942, -3.41041, -3.49954, -3.59207, -3.69467, -3.81331, -3.96048, -4.15626, -4.43863, -4.90479, -5.79363, -6.24746, -4.26896, -3.14354, -2.44187, -1.9507, -1.57115, -1.23503, -0.893369, -0.528228, -0.0869591, 0.616627, 0.406154, -0.479933, -0.479933]]]} test_df = pd.DataFrame(testdata, index=['time']) # 序列化a列 test_df['a'] = test_df['a'].apply(lambda x: json.dumps(np.array(x).tolist())) # 设置时间为索引 test_df = test_df.set_index('time') # 写入数据库 test_df.to_sql(name='Data2_mcw_conv', con=conn, if_exists='replace', index=True) # 验证读取还原 read_df = pd.read_sql('SELECT * FROM Data2_mcw_conv', con=conn, index_col='time') read_df['a'] = read_df['a'].apply(lambda x: np.array(json.loads(x))) print("还原后数组维度:", read_df['a'].iloc[0].shape) # 输出:还原后数组维度: (1, 50)
内容的提问来源于stack exchange,提问作者xyiong
相关产品推荐
相关产品推荐

