0

I would like to combine multiple numpy arrays by the order of the index. Here is what I mean: Suppose I have two numpy arrays like

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

How can I combine these arrays such that the output is

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

concatenate and append will place a and b "next" to each other, which is not quite what I want.

Numpy's repeat and tile functions serve as an analogy here. For example

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

tile is to concatenate as repeat is to ???

A solution:

I've been able to accomplish this with

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

Is there a better way to do this?

1 Answer 1

2

Your solution is pretty good. You can speed it up a bit by doing the stacking already in FORTRAN order:

timeit(lambda:np.stack([a,b]).flatten("F"))
# 11.13118030806072
timeit(lambda:np.array([a,b],order="F").ravel(order="K"))
# 3.0580440941266716
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.