この記事は過去のエラー解決メモを整理したものです。
現在の推奨手順とは異なる可能性があります。
公式ドキュメントを確認して最新情報と差分がないかを確認してください。
事象
DataFrameをPostgreSQLに挿入するため、df.to_sql(table, engine, if_exists='replace', index=True, method='multi', chunksize=1000) を実行したところエラーが発生した。
psycopg2: can't adapt type 'numpy.int64'
環境
- Windows 10
- Python 3.9.6
- pandas
- NumPy
- psycopg2
- PostgreSQL
- VSCode 1.63.0
原因
考えられる原因は次の2つ。
- psycopg2が
numpy.int64をそのまま扱えない。 - PostgreSQLへ渡しているデータの形が想定と異なっている。まずはこちらを確認する。
[ValueError: The truth value of a DataFrame is ambiguous. エラー](ValueError DataFrame truth value ambiguous.md)
対策
-
psycopg2.extensionsを使って、numpy.int64などのNumPy型をpsycopg2で扱えるようにする。
import numpy as np
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)
def addapt_numpy_float32(numpy_float32):
return AsIs(numpy_float32)
def addapt_numpy_int32(numpy_int32):
return AsIs(numpy_int32)
def addapt_numpy_array(numpy_array):
return AsIs(tuple(numpy_array))
register_adapter(np.float64, addapt_numpy_float64)
register_adapter(np.int64, addapt_numpy_int64)
register_adapter(np.float32, addapt_numpy_float32)
register_adapter(np.int32, addapt_numpy_int32)
register_adapter(np.ndarray, addapt_numpy_array)