Skip to content Skip to sidebar Skip to footer

Extraction Of Common Element In Given Arrays To Make A New Array

In the example below, data1, data2, and data3 are the given arrays. Now, I have to find out the element which exist in all the given arrays. Then, I have to make new array includin

Solution 1:

Use Boolean indexing

import numpy as np
result = np.empty_like(data1, dtype=float)
# Make an array of True-False values storing which indices are the same
indices = (data1==data2) * (data2==data3)
result[indices] = data1[indices]
result[~indices] = np.nan

If you have more arrays, you can do something like this: (assuming the arrays are in a list)

# construct the list of arrays
data = []
for i in xrange(8):
    data.append(np.random.randint(0,2, (20, 20)))
indices = data[0] == data[1]
for i in xrange(2, 8):
    indices *= (data[0] == data[i])
result = np.empty_like(data[1], dtype=float)
result[indices] = data1[indices]
result[~indices] = np.nan
result

It would be much better, however, if each array were just a slice of a 3D array. It was shown in another answer that, given several arrays, you can make a 3D array from them and then use np.where. That is a valid approach. I'll show how to do this with array broadcasting here. In this case we can do the following

# construct 3D array with random data
# each data array will be a slice of this array, e.g. data[0], data[1], etc.
data = np.random.randint(0, 3, (3, 4, 5))
# make an empty array to store the results as before
result = np.empty_like(data[0], dtype=float)
# use broadcasting to test for equality
indices = np.all(data == data[0], axis=0)
# Do the assignment as before
result[indices] = data[0][indices]
result[~indices] = np.nan
result

Post a Comment for "Extraction Of Common Element In Given Arrays To Make A New Array"