# Conditional operation between numpy array of different shapes

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

# subtract data1 from data2 for rows with common values
``````[[ 0  0  0  0]