Skip to main content
 首页 » 编程设计

python之ProgrammingError : (psycopg2. ProgrammingError) 无法适配类型 'numpy.ndarray'

2025年04月02日7zlslch

我正在使用 pandas 创建一个 python 脚本来读取具有多个行值的文件。

读取后,我需要构建这些值的数组,然后将其分配给数据框行值。

我用过的代码是

import re 
import numpy as np 
import pandas as pd 
master_data = pd.DataFrame() 
temp_df = pd.DataFrame() 
new_df = pd.DataFrame() 
 
for f in data: 
 
 
##Reading the file in pandas which is in excel format  
# 
file_df = pd.read_excel(f) 
 
 
filename = file_df['Unnamed: 1'][2] 
 
 
##Skipping first 24 rows to get the required reading values 
column_names = ['start_time','xxx_value'] 
data_df = pd.read_excel(f, names=column_names, skiprows=25) 
 
 
array =np.array([]) 
 
   for i in data_df.iterrows(): 
       array = np.append(array,i[1][1]) 
 
 
   temp_df['xxx_value'] = [array] 
   temp_df['Filename'] = filename 
   temp_df['sub_id']=        
   temp_df['Filename'].str.split('_',1).str[1].str.strip()  
   temp_df['sen_site']=     
   temp_df['Filename'].str.split('_',1).str[0].str.strip() 
   temp_df['sampling_interval'] = 15 
   temp_df['start_time'] = data_df['start_time'][2] 
 
 
   new_df= new_df.append(xxx_df) 
 
   new_df.index = new_df.index + 1 
   new_df=new_df.sort_index() 
   new_df.index.name='record_id' 
 
  new_df = new_df.drop("Filename",1)    ##dropping the Filename as it           
  is not needed to be loaded in postgresql 
 
 ##Rearrange to postgresql format 
 column_new_df = new_df.columns.tolist() 
 column_new_df. 
 insert(4,column_new_df.pop(column_new_df.index('xxx_value'))) 
 new_df = new_df.reindex(columns = column_new_df) 
 
 print(new_df) 

当我尝试将数组数据插入 Postgresql 时,这段代码不起作用。

它给我一个错误说明:

ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'numpy.ndarray'

请您参考如下方法:

我不确定问题出在哪里,因为我在您的代码中看不到您将数据插入 Postgres 的部分。

我的猜测是你给了 Postgres 一个 Numpy 数组:psycopg2 不能处理 Numpy 数据类型,但是将它转换为与 psycopg2 一起工作的原生 Python 类型应该相当容易(例如通过使用 .tolist(方法),如果没有代码,很难给出更准确的信息)。