Skip to main content
 首页 » 编程设计

python之numpy中的二元运算

2025年05月04日16mengfanrong

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

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 (most recent call last) in () ----> 1 resulted = np.array([0 if x < 100 else 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() 

关于我如何推进这项工作有什么想法吗?提前致谢。

请您参考如下方法:

Astype int of boolean 会给你想要的,即

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]]])