为什么这在Python2.7中有效,但在Python3中不起作用,背后的原因是什么?我正在使用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版本有关?谢谢。
发布于 2017-12-12 05:49:38
我认为相关的区别在于NumPy从原生Python类型到其内部类型的自动映射。来自their docs
Warning:
int_
类型不是从Python3中内置的int
继承的,因为类型int
不再是固定宽度的整数类型。
在代码中的某个地方,您会从一个数值结果中获得一个值,在Python2中,这些值是原生的int
s,但是在Python3中,它们可能仍然是numpy.int64
s,因为它不知道将它们转换成什么。我不确定你会怎么解决它。
https://stackoverflow.com/questions/47761866
复制相似问题