Home > other >  Elements overlapping rows and columns
Elements overlapping rows and columns

Time:01-25

Question: Create a array x of shape (n_row.n_col), having first n natural numbers. N = 30, n_row= 6, n_col=5

Print elements, overlapping first two rows and last three columns.

Expected output:

[[2 3 4]
 [7 8 9]]

My output:

[2 3 7 8]

My approach:

x = np.arange (n)

x= x.reshape(n_row,n_col)

a= np. intersectId(x[0:2,],x[:,-3:1])

print (a)

I couldn't think of anything else, please help

CodePudding user response:

I think you were close:

import numpy as np

#I hardcoded these values, but you can put them into a function
x = np.arange(30)
x= x.reshape(6,5)

#These values do not need to change.
a= np.intersect1d(x[:2],x[:,-3:]).reshape(2,3)

print(a)

Note: Since we are specific about taking the first two rows and last three columns, we do not need to change the last reshape, since the intersection will always be a 2x3 matrix.

Output:

[[2 3 4]
 [7 8 9]]

CodePudding user response:

The overlap of row and column slices of the same array is just the combined slice

import numpy as np

x = np.arange(30).reshape(6, 5)
x[:2,-3:]

Output

array([[2, 3, 4],
       [7, 8, 9]])

To compute the overlap by finding same elements is odd but possible

r, c = np.where(np.isin(x, np.intersect1d(x[:2], x[:,-3:])))

x[np.ix_(np.unique(r), np.unique(c))]

Output

array([[2, 3, 4],
       [7, 8, 9]])
  •  Tags:  
  • Related