【发布时间】:2018-11-10 13:41:44
【问题描述】:
我有一个具有如下所示 dtypes 的数据框,我想将数据框插入 postgres 数据库,但由于错误 can't adapt type 'numpy.int64'
id_code int64
sector object
created_date float64
updated_date float64
如何将这些类型转换为原生 Python 类型,例如从 int64(本质上是“numpy.int64”)转换为经典的 int,然后通过 psycopg2 客户端为 postgres 所接受。
data['id_code'].astype(np.int) defaults to int64
仍然可以从一种 numpy 类型转换为另一种类型(例如从 int 转换为 float)
data['id_code'].astype(float)
更改为
dtype: float64
如果有人知道如何将它们转换为有用的经典类型,那么 psycopg2 似乎并不理解 numpy 数据类型。
更新:插入数据库
def insert_many():
"""Add data to the table."""
sql_query = """INSERT INTO classification(
id_code, sector, created_date, updated_date)
VALUES (%s, %s, %s, %s);"""
data = pd.read_excel(fh, sheet_name=sheetname)
data_list = list(data.to_records())
conn = None
try:
conn = psycopg2.connect(db)
cur = conn.cursor()
cur.executemany(sql_query, data_list)
conn.commit()
cur.close()
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
【问题讨论】:
-
你能显示你插入的代码吗?
-
@Michael 当然,更新了问题描述。
-
您是否尝试过将 id_code 定义为 BIGINT?
-
如果您的意思是在数据库端将其定义为 BIGINT,不,我没有尝试这种方法,因为我理解问题是 psycopg2 客户端没有将 numpy 类型映射到 python 本机。
-
Ints 从 DataFrame 中返回为 numpy.int64。
data = [[1],[2]]df = pd.DataFrame(data)print(type(df.iloc[0][0]))导致