Skip to main content
 首页 » 编程设计

python之导致此错误的 Python 2 和 Python 3 之间有什么区别

2024年10月01日6lvdongjie

这在 Python 2.7 中有效但在 Python 3 中无效的原因是什么?我正在使用 psycopg2 将值插入表中,但光标在我的 pandas 数据框中的 column2 上遇到了困难。

In [1]: df.info() 
<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 11565 entries, 0 to 11564 
Data columns (total 3 columns): 
column1    11565 non-null object 
column2    11565 non-null int64 
column3    11565 non-null object 
dtypes: int64(1), object(2) 
memory usage: 271.1+ KB 
 
# Python 2.7 
cur = conn.cursor() 
 
# pass table values  
vals = [cur.mogrify("(%s, %s, %s)", (x, y, z)) for x, y, z in zip(df['column1'], df['column2'],df['column3'])] 
# Great! 

--

# Python 3.5 
cur = conn.cursor() 
 
# pass table values  
vals = [cur.mogrify("(%s, %s, %s)", (x, y, z)) for x, y, z in zip(df['column1'], df['column2'],df['column3'])] 
 
<ipython-input-2-ee4818a2eb52> in <listcomp>(.0) 
      1 # pass table values 
----> 2 vals = [cur.mogrify("(%s, %s, %s)", (x, y, z)) for x, y, z in zip(df['column1'], df['column2'],df['column3'])] 
 
ProgrammingError: can't adapt type 'numpy.int64' 

这是否与不同版本的 psycopg2 本身或底层 Python 版本有关?谢谢。

请您参考如下方法:

我认为相关的区别在于 NumPy 从 native Python 类型到其内部类型的自动映射。来自 their docs :

Warning: The int_ type does not inherit from the int built-in under Python 3, because type int is no longer a fixed-width integer type.

在代码中的某处,您从 numpy 结果中获取了一个值,在 Python 2 中,这些值是原生的 int,但在 Python 3 中,它们可能仍然是 numpy。 int64,因为它不知道将它们转换成什么。我不确定你会如何解决这个问题。