Using numpy to build an array of all combinations of two arrays

后端 未结 10 1433
温柔的废话
温柔的废话 2020-11-22 00:41

I\'m trying to run over the parameters space of a 6 parameter function to study it\'s numerical behavior before trying to do anything complex with it so I\'m searching for a

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 01:22

    Here's yet another way, using pure NumPy, no recursion, no list comprehension, and no explicit for loops. It's about 20% slower than the original answer, and it's based on np.meshgrid.

    def cartesian(*arrays):
        mesh = np.meshgrid(*arrays)  # standard numpy meshgrid
        dim = len(mesh)  # number of dimensions
        elements = mesh[0].size  # number of elements, any index will do
        flat = np.concatenate(mesh).ravel()  # flatten the whole meshgrid
        reshape = np.reshape(flat, (dim, elements)).T  # reshape and transpose
        return reshape
    

    For example,

    x = np.arange(3)
    a = cartesian(x, x, x, x, x)
    print(a)
    

    gives

    [[0 0 0 0 0]
     [0 0 0 0 1]
     [0 0 0 0 2]
     ..., 
     [2 2 2 2 0]
     [2 2 2 2 1]
     [2 2 2 2 2]]
    

提交回复
热议问题