postgresql psycopg2:将带有NaN的numpy数组插入到表中

mnowg1ta  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(225)

下面的代码可以很好地将多维numpy数组插入到表中

  1. def adapt_numpy_array(numpy_array):
  2. return AsIs(numpy_array.tolist())
  3. register_adapter(np.ndarray, adapt_numpy_array)
  4. register_adapter(np.int32, AsIs)
  5. register_adapter(np.int64, AsIs)
  6. register_adapter(np.float64, AsIs)

字符串
但是,如果数组包含NaN,则会中断:
psycopg2.errors.UndefinedColumn:FEHLER:Spalte »nan«未定义行2:.6000.0,692000.0,732000.0,830000.0,928000.0],[nan,nan,..
将适配器更改为

  1. def adapt_numpy_array(numpy_array):
  2. return numpy_array.tolist()
  3. def nan_to_null(f,
  4. _NULL=psycopg2.extensions.AsIs('NULL'),
  5. _Float=psycopg2.extensions.Float):
  6. if not np.isnan(f):
  7. return _Float
  8. return _NULL
  9. register_adapter(float, nan_to_null)


产生另一个错误
AttributeError:'list'对象没有属性'getquoted'
为什么第二个代码中断,psycopg2应该遍历列表并将每个浮点数替换为它的值或NULL?如何在存在NaN的情况下将numpy数组插入SQL表?

gopyfrb3

gopyfrb31#

技巧是将numpy数组转换为字符串,并通过NULL正确表示NaN值。格式化的字符串然后可以由AsIs适配器 Package 。

  1. import numpy as np
  2. from psycopg2.extensions import register_adapter, AsIs
  3. def adapt_numpy_array(numpy_array):
  4. return AsIs(str(numpy_array.tolist()).replace("nan", "NULL"))
  5. register_adapter(np.ndarray, adapt_numpy_array)

字符串
不确定这是否是最优雅的解决方案,但它确实可以处理我抛出的任何numpy数组。

相关问题