Skip to main content
 首页 » 编程设计

python之非零函数帮助,Python Numpy

2025年05月04日15jpfss

我有两个数组,我有一个像这样的复杂条件:new_arr<0 and old_arr>0 我正在使用非零但出现错误。我的代码是这样的:

    indices = nonzero(new_arr<0 and old_arr>0) 

我试过:

    indices = nonzero(new_arr<0) and nonzero(old_arr>0) 

但它给了我不正确的结果。

有什么办法解决这个问题吗?有没有办法从两个非零语句中获取公共(public)索引。例如,如果:

    indices1 = nonzero(new_arr<0) 
    indices2 = nonzero(old_arr>0) 

这两个索引将包含:

   indices1 = array([0, 1, 3]) 
   indices2 = array([2, 3, 4]) 

正确的结果是从这两个元素中获取公共(public)元素(在本例中为元素 3)。像这样:

    result = common(indices1, indices2) 

请您参考如下方法:

尝试 indices = nonzero((new_arr < 0) & (old_arr > 0)) :

In [5]: import numpy as np 
 
In [6]: old_arr = np.array([ 0,-1, 0,-1, 1, 1, 0, 1]) 
 
In [7]: new_arr = np.array([ 1, 1,-1,-1,-1,-1, 1, 1]) 
 
In [8]: np.nonzero((new_arr < 0) & (old_arr > 0)) 
Out[8]: (array([4, 5]),)