【问题标题】:Reduction of NumPy bitwise_and functionNumPy bitwise_and 函数的缩减
【发布时间】:2016-12-06 23:14:54
【问题描述】:

考虑以下 numpy 数组数组:

x = np.array([2]*4, dtype=np.uint8)

这只是一个由四个 2 组成的数组。

我想对该数组执行按位和归约:

y = np.bitwise_and.reduce(x)

我希望结果是:

2

因为数组的每个元素都是相同的,所以连续的 AND 应该产生相同的结果,但我得到的是:

0

为什么会出现差异?

【问题讨论】:

  • Related question 有一个巧妙的解决方法,以防你被当前的 Python 安装卡住了

标签: python arrays numpy reduction


【解决方案1】:

reduce docstring中,解释了函数等价于

 r = op.identity # op = ufunc
 for i in range(len(A)):
   r = op(r, A[i])
 return r

问题是np.bitwise_and.identity是1:

In [100]: np.bitwise_and.identity
Out[100]: 1

要使reduce 方法按预期工作,标识必须是所有位都设置为 1 的整数。

以上代码是使用 numpy 1.11.2 运行的。问题一直fixed in the development version of numpy

In [3]: np.__version__
Out[3]: '1.13.0.dev0+87c1dab'

In [4]: np.bitwise_and.identity
Out[4]: -1

In [5]: x = np.array([2]*4, dtype=np.uint8)

In [6]: np.bitwise_and.reduce(x)
Out[6]: 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 2018-07-25
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2017-03-26
    相关资源
    最近更新 更多