I'm working with a problem using numpy arrays and I hit a roadblock, basically I have two arrays, one with a 2D numpy array and the other is a 1D numpy which represents some index of the 2D array, what I need is to use pairs of this indexes to extract a 2D numpy array from the original 2D array, I did something, but I'm sure it can be better, so I'm asking for advice. Here is my code:
import numpy as np
import itertools
x = np.arange(25).reshape(5, 5) #Original Array
#x = [[ 0 1 2 3 4]
# [ 5 6 7 8 9]
# [10 11 12 13 14]
# [15 16 17 18 19]
# [20 21 22 23 24]]
y = np.array([0, 2, 4]) #Indexes
idx = list(itertools.product(y, repeat = 2)) #This create a combination of the indexes to act as my coordinates from the array
#idx = [(0, 0), (0, 2), (0, 4), (2, 0), (2, 2), (2, 4), (4, 0), (4, 2), (4, 4)]
newarray = np.array([x[i] for i in idx]).reshape(3, 3) #This uses the tuples from before to extract the values of the original array
#newarray = [[ 0 2 4]
# [10 12 14] #The extracted array
# [20 22 24]]
So it works, but I think there is a lot to improve, for example, in the final step I use a list comprehesion and then a numpy array, and then a reshape, also I'm not sure if it's okay to create all the combinations of the index array maybe there is a easier way, so any advice will be appreciated, thank you!