Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two numpy arrays:

A = np.array([1, 3, 5, 7])
B = np.array([2, 4, 6, 8])

and I want to get the following from combining the two:

C = [1, 2, 3, 4, 5, 6, 7, 8]

I'm able to get something close by using zip, but not quite what I'm looking for:

>>> zip(A, B)
[(1, 2), (3, 4), (5, 6), (7, 8)]

How do I combine the two numpy arrays element wise?


I did a quick test of 50,000 elements in each array (100,000 combined elements). Here are the results:

User Ma3x:      Time of execution: 0.0343832323429      Valid Array?:  True
User mishik:    Time of execution: 0.0439064509613      Valid Array?:  True
User Jaime:     Time of execution: 0.02767023558        Valid Array?:  True

Tested using Python 2.7, Windows 7 Enterprise 64-bit, Intel Core i7 2720QM @2.2 Ghz Sandy Bridge, 8 GB Mem

share|improve this question
Here's a link to the code that I used to test this. – KronoS yesterday

4 Answers

up vote 2 down vote accepted

Use np.insert:

>>> A = np.array([1, 3, 5, 7])
>>> B = np.array([2, 4, 6, 8])
>>> np.insert(B, np.arange(len(A)), A)
array([1, 2, 3, 4, 5, 6, 7, 8])
share|improve this answer

You can also use slices :

C = np.empty((A.shape[0]*2), dtype=A.dtype)
C[0::2] = A
C[1::2] = B
share|improve this answer

Some answers suggested sorting, but since you want to combine them element-wise sorting won't achieve the same result.

Here is one way to do it

C = []
for elem in zip(A, B):
    C.extend(elem)
share|improve this answer

You can try this:

C = sorted(A.tolist() + B.tolist())
  1. A.tolist() will yield [1, 3, 5, 7]
  2. B.tolist() will yield [2, 4, 6, 8]
  3. A.tolist() + B.tolist() - [1, 3, 5, 7, 2, 4, 6, 8]
  4. sorted(...) - [1, 2, 3, 4, 5, 6, 7, 8]

Without sorting:

C = [y for x in zip(A, B) for y in x]
share|improve this answer
I don't want the elements to be sorted, as these are actually data samples that aren't in order of value. Your second option was used in my testing. – KronoS yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.