Home > Blockchain >  How to merge two numpy arrays for each number in the first?
How to merge two numpy arrays for each number in the first?

Time:12-04

I have two arrays e.g. a = [1, 2] and b = [3, 4]. What i want is to create an array that has all of b for each a: c = [[1, 3], [1, 4], [2, 3], [2, 4]]. How do i do this using numpy?

CodePudding user response:

Use np.meshgrid:

import numpy as np

a = [1, 2]
b = [3, 4]


def mesh(values):
    return np.array(np.meshgrid(*values)).T.reshape(-1, len(values))


res = mesh([a, b])
print(res)

Output

[[1 3]
 [1 4]
 [2 3]
 [2 4]]
  • Related