Conditional operation between numpy array of different shapes

Advertisements

i have two numpy arrays of different shapes.

import numpy

data1 = numpy.array([[1, 2, 3, 4], [2, 6, 7, 8], [3, 10, 11, 12], [4, 13, 13, 12], [5, 10, 1, 12]])
data2 = numpy.array([[1, 2, 3, 4], [2, 6, 7, 8], [4, 13, 13, 12], [5, 10, 1, 12]])

I want to make an operation only on the elements of the array that have a value in common in the first column.

inter = numpy.intersect1d(data1[:,0], data2[:,0])

With the intersect1D I get the values on the first column that are shared but how can i do an operation (lets say substract the array 1 to the array 2) only on the rows that have this values in the first column?

Thank you,

Davide

>Solution :

You can use Boolean indexing with the numpy arrays to extract only the rows that have the common values in the first column. Here’s an example of how to subtract data1 from data2 for the rows that have the common values in the first column:

import numpy as np

data1 = np.array([[1, 2, 3, 4], [2, 6, 7, 8], [3, 10, 11, 12], [4, 13, 13, 12], [5, 10, 1, 12]])
data2 = np.array([[1, 2, 3, 4], [2, 6, 7, 8], [4, 13, 13, 12], [5, 10, 1, 12]])

# get common values in the first column
common_vals = np.intersect1d(data1[:,0], data2[:,0])

# boolean indexing to extract rows with common values
mask1 = np.isin(data1[:,0], common_vals)
mask2 = np.isin(data2[:,0], common_vals)

# subtract data1 from data2 for rows with common values
result = data2[mask2] - data1[mask1]

print(result)

Output will be

[[ 0  0  0  0]
 [ 2  3  6  4]
 [ 1  3  2  0]]

Note that the resulting array has only the rows with the common values in the first column and the operation has been performed only on those rows.

Leave a ReplyCancel reply