首页 > 解决方案 > numpy 将数组与索引排序结合起来

问题描述

我想按索引的顺序组合多个 numpy 数组。这就是我的意思:假设我有两个像

>>> a = [0, 1, 2, 3]
>>> b = [-5, -6, -7, -8]

如何组合这些数组以使输出为

c = np.combination_function((a,b))
>>> c = [0 -5, 1, -6, 2, -7, 3, -8]

concatenate并将彼此append放置ab“相邻”,这不是我想要的。

Numpyrepeattile函数在此用作类比。例如

np.repeat([3, 4, 2], 2)
>>> [3, 3, 4, 4, 2, 2] # two 3's, then two 4's, then two 2's. This is what I want
np.tile([3, 4, 2], 2)
>>> [3, 4, 2, 3, 4, 2] # [3,4,2] twice. This is not what I want

tileconcatenate原样repeat_???

一个办法:

我已经能够做到这一点

c = np.stack((a,b)).flatten('F')

有一个更好的方法吗?

标签: pythonarraysnumpy

解决方案


你的解决方案非常好。您可以通过按 FORTRAN 顺序进行堆叠来加快速度:

timeit(lambda:np.stack([a,b]).flatten("F"))
# 11.13118030806072
timeit(lambda:np.array([a,b],order="F").ravel(order="K"))
# 3.0580440941266716

推荐阅读