您可以转置和展平数组:
d = numpy.array([a, b, c]).T.flatten()
组合数组的另一种方法是使用numpy.vstack()
:
d = numpy.vstack((a, b, c)).T.flatten()
(顺便说一句,我不知道哪个更快。)
编辑:响应Nicolas Barbey 的回答,这里是如何只复制一次数据:
d = numpy.empty((len(a), 3), dtype=a.dtype)
d[:, 0], d[:, 1], d[:, 2] = a, b, c
d = d.ravel()
这段代码确保数据以ravel()
不需要复制的方式布局,而且确实比我机器上的原始代码快很多:
In [1]: a = numpy.arange(0, 30000, 3)
In [2]: b = numpy.arange(1, 30000, 3)
In [3]: c = numpy.arange(2, 30000, 3)
In [4]: def f(a, b, c):
...: d = numpy.empty((len(a), 3), dtype=a.dtype)
...: d[:, 0], d[:, 1], d[:, 2] = a, b, c
...: return d.ravel()
...:
In [5]: def g(a, b, c):
...: return numpy.vstack((a, b, c)).T.ravel()
...:
In [6]: %timeit f(a, b, c)
10000 loops, best of 3: 34.4 us per loop
In [7]: %timeit g(a, b, c)
10000 loops, best of 3: 177 us per loop