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

后端 未结 10 1306
温柔的废话
温柔的废话 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:38

    For a pure numpy implementation of Cartesian product of 1D arrays (or flat python lists), just use meshgrid(), roll the axes with transpose(), and reshape to the desired ouput:

     def cartprod(*arrays):
         N = len(arrays)
         return transpose(meshgrid(*arrays, indexing='ij'), 
                          roll(arange(N + 1), -1)).reshape(-1, N)
    

    Note this has the convention of last axis changing fastest ("C style" or "row-major").

    In [88]: cartprod([1,2,3], [4,8], [100, 200, 300, 400], [-5, -4])
    Out[88]: 
    array([[  1,   4, 100,  -5],
           [  1,   4, 100,  -4],
           [  1,   4, 200,  -5],
           [  1,   4, 200,  -4],
           [  1,   4, 300,  -5],
           [  1,   4, 300,  -4],
           [  1,   4, 400,  -5],
           [  1,   4, 400,  -4],
           [  1,   8, 100,  -5],
           [  1,   8, 100,  -4],
           [  1,   8, 200,  -5],
           [  1,   8, 200,  -4],
           [  1,   8, 300,  -5],
           [  1,   8, 300,  -4],
           [  1,   8, 400,  -5],
           [  1,   8, 400,  -4],
           [  2,   4, 100,  -5],
           [  2,   4, 100,  -4],
           [  2,   4, 200,  -5],
           [  2,   4, 200,  -4],
           [  2,   4, 300,  -5],
           [  2,   4, 300,  -4],
           [  2,   4, 400,  -5],
           [  2,   4, 400,  -4],
           [  2,   8, 100,  -5],
           [  2,   8, 100,  -4],
           [  2,   8, 200,  -5],
           [  2,   8, 200,  -4],
           [  2,   8, 300,  -5],
           [  2,   8, 300,  -4],
           [  2,   8, 400,  -5],
           [  2,   8, 400,  -4],
           [  3,   4, 100,  -5],
           [  3,   4, 100,  -4],
           [  3,   4, 200,  -5],
           [  3,   4, 200,  -4],
           [  3,   4, 300,  -5],
           [  3,   4, 300,  -4],
           [  3,   4, 400,  -5],
           [  3,   4, 400,  -4],
           [  3,   8, 100,  -5],
           [  3,   8, 100,  -4],
           [  3,   8, 200,  -5],
           [  3,   8, 200,  -4],
           [  3,   8, 300,  -5],
           [  3,   8, 300,  -4],
           [  3,   8, 400,  -5],
           [  3,   8, 400,  -4]])
    

    If you want to change the first axis fastest ("FORTRAN style" or "column-major"), just change the order parameter of reshape() like this: reshape((-1, N), order='F')

提交回复
热议问题