psycopg2: can't adapt type 'numpy.int64'

same problem here, successfully solve this problem after I transform series to nd.array and int.

you can try as following:

data['id_code'].values.astype(int)

--

update:

if the value including NaN, it still wrong. It seems that psycopg2 can't explain the np.int64 format, therefore the following methods works for me.

import numpy as np
from psycopg2.extensions import register_adapter, AsIs
psycopg2.extensions.register_adapter(np.int64, psycopg2._psycopg.AsIs)


I'm not sure why your data_list contains NumPy data types, but the same thing happens to me when I run your code. Here is an alternative way to construct data_list that so that integers and floats end up as their native python types:

data_list = [list(row) for row in data.itertuples(index=False)] 

Alternate approach

I think you could accomplish the same thing in fewer lines of code by using pandas to_sql:

import sqlalchemy
import pandas as pd
data = pd.read_excel(fh, sheet_name=sheetname)
engine = sqlalchemy.create_engine("postgresql://username@hostname/dbname")
data.to_sql(engine, 'classification', if_exists='append', index=False)

Add below somewhere in your code:

import numpy
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
    return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
    return AsIs(numpy_int64)
register_adapter(numpy.float64, addapt_numpy_float64)
register_adapter(numpy.int64, addapt_numpy_int64)

Tags:

Numpy

Psycopg2