Home > Software design >  2 different specified elements from 2 numpy arrays
2 different specified elements from 2 numpy arrays

Time:03-23

I have two numpy arrays with 0s and 1s in them. How can I find the indexes with 1 in the first array and 0 in the second?

I tried np.logical_and

But got error message (builtin_function_or_method' object is not subscriptable)

CodePudding user response:

Use np.where(arr1==1) and np.where(arr2==0)

CodePudding user response:

import numpy as np


array1 = np.array([0,0,0,1,1,0,1])
array2 = np.array([0,1,0,0,1,0,1])


ones = np.where(array1 == 1)
zeroes = np.where(array2 == 0)
    
print("array 1 has 1 at",ones)
print("array 2 has 0 at",zeroes)

returns:

array 1 has 1 at (array([3, 4, 6]),)
array 2 has 0 at (array([0, 2, 3, 5]),)

CodePudding user response:

I'm not sure if theres some built-in numpy function that will do this for you, since it's a fairly specific problem. EDIT: there is, see bottom

Nonetheless, if one were to exist, it would have to be a linear time algorithm if you're passing in a bare numpy array, so writing your own isn't difficult.

If I have any numpy array (or python array) myarray, and I want a collection of indices where some object myobject appears, we can do this in one line using a list comprehension:

indices = [i for i in range(len(myarray)) if myarray[i] == myobject]

So what's going on here?

A list comprehension works in the following format:

[<output> for <input> in <iterable> if <condition>]

In our case, <input> and <output> are the indices of myarray, and the <condition> block checks if the value at the current index is equal to that of our desired value.

Edit: as White_Sirilo helpfully pointed out, numpy.where does the same thing, I stand corrected

CodePudding user response:

Let's say your arrays are called j and k. The following code returns all indices where j[index] = 1 and k[index] = 0 if both arrays are 1-dimensional. It also works if j and k are different sizes.

idx_1 = np.where(j == 1)[0]
idx_2 = np.where(k == 0)[0]

final_indices = np.intersect1d(idx_1, idx_2, return_indices=False)

If your array is 2-dimensional, you can use the above code in a function and then go row-by-row. There are almost definitely better ways to do this, but this works in a pinch.

CodePudding user response:

tow numpy array given in problem. array1 and array2

just use one_index=np.where(array1==1) and zero_index=np.where(array2==0)

  • Related