I am learning numpy, and I need to figure out how to create a new numpy array from two defined numpy arrays, where the new array is effectively a bunch of subarrays created from the elements of array 1 being "mapped" to the elements of array 2.
What I mean is, that for:
array1 = [6,8,9]
array2 = [1, 2, 3]
then the resultant array needs to equal:
[[6,1], [6,2], [6,3], [8,1], [8,2], [8,3], [9,1], [9,2], [9,3]]
I would like to know how to do this with numpy-specific functions (so no 'for' loops for iterating over the array elements individually)
CodePudding user response:
Use np.meshgrid
:
import numpy as np
array1 = [6, 8, 9]
array2 = [1, 2, 3]
def mesh(values):
return np.array(np.meshgrid(*values)).T.reshape(-1, len(values))
res = mesh([array1, array2])
print(res)
Output
[[6 1]
[6 2]
[6 3]
[8 1]
[8 2]
[8 3]
[9 1]
[9 2]
[9 3]]