1

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)

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.