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

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

    The following numpy implementation should be approx. 2x the speed of the given answer:

    def cartesian2(arrays):
        arrays = [np.asarray(a) for a in arrays]
        shape = (len(x) for x in arrays)
    
        ix = np.indices(shape, dtype=int)
        ix = ix.reshape(len(arrays), -1).T
    
        for n, arr in enumerate(arrays):
            ix[:, n] = arrays[n][ix[:, n]]
    
        return ix
    

提交回复
热议问题