0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

psycopg2: can't adapt type 'numpy.int64' エラーが発生する

0
Posted at

この記事は過去のエラー解決メモを整理したものです。
現在の推奨手順とは異なる可能性があります。
公式ドキュメントを確認して最新情報と差分がないかを確認してください。

事象

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つ。

  1. psycopg2が numpy.int64 をそのまま扱えない。
  2. 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)

参考情報

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?