【问题标题】:Different behavior of pandas.Series operator /= in Python 2 vs Python 3python 2 与 Python 3 中 pandas.Series 运算符 /= 的不同行为
【发布时间】:2018-04-02 23:38:47
【问题描述】:

这是一段简短的 python 代码,其中出现了 anaconda2 和 anaconda3 版本之间的一个非常奇怪的区别:

import pandas as pd


def div(x):
    to_sum = x['a']
    to_sum /= 2


def mul(x):
    to_sum = x['a']
    to_sum *= 2


a = pd.DataFrame(data=[[10.0, 20.0]], columns=['a', 'b'])
print('init:')
print(a)

div(a)
print('after div:')
print(a)

mul(a)
print('after mul:')
print(a)

当我这样运行时:

echo "python3:" && \
~/work/Programs/Anaconda/anaconda3/bin/python3 tmp.py && \
echo && \
echo "python2:" && \
~/work/Programs/Anaconda/anaconda2/bin/python2 tmp.py

对于不同的版本,我得到的结果主要是不同的:

python3:
init:
      a     b
0  10.0  20.0
after div:
     a     b
0  5.0  20.0
after mul:
      a     b
0  10.0  20.0

python2:
init:
      a     b
0  10.0  20.0
after div:
      a     b
0  10.0  20.0
after mul:
      a     b
0  20.0  20.0

根据我对 python 的理解,python3 运行证明了正确的行为。为什么operator /=不影响python2中的函数参数?更重要的是,为什么 operator *= 会影响它??!

我正在使用 Anaconda 官方网站上的 python 和 pandas。版本是:(python 3.6.0 with pandas 0.19.2)和(python 2.7.13 with pandas 0.20.3)

编辑 1: 尝试这个整数(即a = pd.DataFrame(data=[[10, 20]], columns=['a', 'b'], dtype='int'))给我带来:

python3:
init:
    a   b
0  10  20
after div:
     a   b
0  5.0  20
after mul:
      a   b
0  10.0  20

python2:
init:
    a   b
0  10  20
after div:
    a   b
0  10  20
after mul:
    a   b
0  20  20

【问题讨论】:

  • 我没有要测试的python 2,但这似乎是整数和实数除法之间的基本区别。第一个更改 dtype,因此返回一个副本,第二个具有相同的 dtype,因此返回一个视图。如果你在整数上尝试会发生什么?
  • @ayhan 你确定吗?我的理解是它与大熊猫防止复制有关。我可能需要重新审视我的答案。
  • @cᴏʟᴅsᴘᴇᴇᴅ 不完全确定,因为我无法在 Python 2 上对其进行测试,但使用to_sum = to_sum // 2 Python 3 返回的结果与 OP 的 Python 2 结果相同。
  • @ayhan 我明白了,我相信你比我更了解它,所以请随时写一个答案 :-) 我已经删除了我的。
  • @cᴏʟᴅsᴘᴇᴇᴅ 谢谢。 :) 如果有人可以用 Python 2 说明会更好。你有吗?如果是这样,请随时修改您的答案。

标签: python python-2.7 python-3.x pandas numpy


【解决方案1】:

这是Pandas issue 12962pandas.core.ops 中的错误导致 __idiv__ 缺少将更新系列而不是返回副本的处理。将 Pandas 更新到至少 0.21 应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2021-11-16
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多