【问题标题】:What difference between Python 2 and Python 3 is causing this error?Python 2 和 Python 3 之间有什么区别导致此错误?
【发布时间】:2018-06-21 06:49:59
【问题描述】:

这在 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 版本有关?谢谢。

【问题讨论】:

    标签: python python-3.x python-2.7 psycopg2


    【解决方案1】:

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

    警告int_ 类型不会继承自 Python 3 下的内置 int,因为类型 int 不再是固定宽度的整数类型。

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

    【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2021-12-03
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    相关资源
    最近更新 更多