4

I have two numpy array's a and b of length 53 and 82 respectively. I would like to merge them into a single array because I want to use the 53+82=135 length array say call it c for plotting.

I tried

c = a+b 

but I am getting ValueError: shape mismatch: objects cannot be broadcast to a single shape

Is this possible?

2 Answers 2

5

You need to use numpy.concatenate instead of array addition

c = numpy.concatenate((a, b))

Implementation

import numpy as np
a = np.arange(53)
b = np.arange(82)
c = np.concatenate((a, b))

Output

c.shape
(135, )
Sign up to request clarification or add additional context in comments.

1 Comment

what if a and b have different shape? (ex: a.shape=(12,8), b.shape=(12,))
4

Use numpy.concatenate:

In [5]: import numpy as np

In [6]: a = np.arange(5)                                                                         

In [7]: b = np.arange(11)                                                                        

In [8]: np.concatenate((a, b))                                                                   
Out[8]: array([ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

For 1-D arrays you can also use numpy.hstack:

In [9]: np.hstack((a, b))                                                                       
Out[9]: array([ 0,  1,  2,  3,  4,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]

3 Comments

I get the error that "only integer scalars can be converted to scalar index"
@DineshVG Share your input data?
Something similar to this - 0.00764538, 0.00871098, 0.00959187, 0.01028805, 0.00884634 for one array and 0.17873864, 0.1273831 , 0.07530486, 0.08724997, 0.07698863, 0.04452086, 0.04699075, 0.06169301, 0.08862764, 0.12403291, 0.26097335, 0.49944897, 0.4297591 , 0.37918886 for the second array...

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.