numpy中的二进制操作

时间:2018-01-03 14:57:13

标签: python numpy

我有一个看起来像这样的数组,

array([[[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    ..., 
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024]],

   ..., 
   [[-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],
    [-1024, -1024, -1024, ..., -1024, -1024, -1024],

它是一个有许多独特元素的冗长数组,如何进行操作,如果值大于100,则使值为1,否则使所有值为0。

我试过

resulted  = np.array([0 if x < 100 else 1 for x in new_one])

但我明白了,

  

ValueError Traceback(最近一次调用   持续)        in()       ----&GT; 1结果= np.array([0如果x&lt; 100,其他1 for x in new_one])

<ipython-input-72-77697094b8bd> in <listcomp>(.0)
----> 1 resulted  = np.array([0 if x < 100 else 1 for x in new_one])

ValueError: The truth value of an array with more than one element is        ambiguous. Use a.any() or a.all()

关于如何实现这一目标的任何想法?提前致谢。

2 个答案:

答案 0 :(得分:6)

布尔的Astype int会给你想要的东西,即

arr = np.array([[[-1024, -1024, -1024, 0, -1024, -1024, -1024],
[-1024, -1024, -1024, 150, -1024, -1024, -1024],
[-1024, -1024, -1024,300, -1024, -1024, -1024]]])


(arr>100).astype(int)

array([[[0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0]]])

答案 1 :(得分:1)

您可以直接在numpy数组上比较运算符:

new_one >= 100

这将构造一个与new_one具有相同形状的数组,除非在True的对应元素大于或等于的情况下填充new_one的布尔值到100,反之亦然。

由于True充当1而False充当0,因此这应该足够了。如果你真的想要整数,你可以使用:

(new_one >= 100).astype(int)