首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python 2和Python 3之间的什么差异导致了此错误?

Python 2和Python 3之间的什么差异导致了此错误?
EN

Stack Overflow用户
提问于 2017-12-12 05:39:17
回答 1查看 617关注 0票数 2

为什么这在Python2.7中有效,但在Python3中不起作用,背后的原因是什么?我正在使用psycopg2向表中插入值,但是游标在我的pandas数据帧中使用column2时遇到了困难。

代码语言:javascript
运行
复制
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!

--

代码语言:javascript
运行
复制
# 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版本有关?谢谢。

EN

回答 1

Stack Overflow用户

发布于 2017-12-12 05:49:38

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

Warningint_类型不是从Python3中内置的int继承的,因为类型int不再是固定宽度的整数类型。

在代码中的某个地方,您会从一个数值结果中获得一个值,在Python2中,这些值是原生的ints,但是在Python3中,它们可能仍然是numpy.int64s,因为它不知道将它们转换成什么。我不确定你会怎么解决它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47761866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档