Python错误:“错误绑定参数可能不支持类型”

2024-04-26 13:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数据框中有一列“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],...]]

我被告知这是一个numpy数组(不确定是否是这种情况,如果我错了请纠正我…)

我希望使用pandas to_sql方法将此数据帧放入sql数据库

为此,我需要将此“对象”转换为sql接受的数据类型,例如字符串。
我必须能够将其作为字符串写入,然后将其作为numpy数组(或其他任何数组)检索

然而,我有一个标题中提到的错误

我的代码目前有点像这样:

import pandas as pd
import sqlite3 as sql
import sqlalchemy
import numpy as np
import io

from datetime import datetime

time = datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')

testdata = {'time': time , '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]]]}  
testdata = pd.DataFrame(testdata,index=['time'])
testdata
test_rows=[]
for index,row in testdata.iterrows():
  t=row['time']
  a=row['a'].astype('str')
  new_rows = {'time': t , 'a':a}
  test_rows.append(pd.Series(new_rows))

testframe = pd.DataFrame(test_rows)
testframe.set_index('time')
print(testframe.dtypes)
testframe

testframe.to_sql(name='Data2_mcw_conv',con=conn,if_exists='replace',index=True)

输出:

time    datetime64[ns]
a               object
dtype: object
---------------------------------------------------------------------------
InterfaceError                            Traceback (most recent call last)
<ipython-input-82-c434bf1560a6> in <module>()
     27 testframe
     28 
---> 29 testframe.to_sql(name='testframe',con=conn,if_exists='replace',index=True)
     30 
     31 

4 frames
/usr/local/lib/python3.7/dist-packages/pandas/io/sql.py in _execute_insert(self, conn, keys, data_iter)
   1553     def _execute_insert(self, conn, keys, data_iter):
   1554         data_list = list(data_iter)
-> 1555         conn.executemany(self.insert_statement(num_rows=1), data_list)
   1556 
   1557     def _execute_insert_multi(self, conn, keys, data_iter):

InterfaceError: Error binding parameter 2 - probably unsupported type.

在尝试使用to_sql转换为sql之前,索引似乎是一个整数而不是时间,即使我使用set_index显式地将时间设置为索引

从这里开始,我有以下问题:

  1. 如何纠正此错误
  2. 由于某种原因,我的索引是一个整数,我如何使时间列成为索引

任何帮助都将不胜感激


Tags: to数据importselfsqldataindextime