I have two simple one-dimensional arrays in NumPy. I should be able to concatenate them using numpy.concatenate. But I get this error for the code below:
TypeError: only length-1 arrays can be converted to Python scalars
Code
import numpy
a = numpy.array([1, 2, 3])
b = numpy.array([5, 6])
numpy.concatenate(a, b)
%pylab
vector_a = r_[0.:10.]#short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]print vector_a
print vector_b
print vector_c,'\n\n'
a = ones((3,4))*4print a,'\n'
c = array([1,1,1])
b = c_[a,c]print b,'\n\n'
a = ones((4,3))*4print a,'\n'
c = array([[1,1,1]])
b = r_[a,c]print b
print type(vector_b)
An alternative ist to use the short form of “concatenate” which is either “r_[…]” or “c_[…]” as shown in the example code beneath (see http://wiki.scipy.org/NumPy_for_Matlab_Users for additional information):
%pylab
vector_a = r_[0.:10.] #short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]
print vector_a
print vector_b
print vector_c, '\n\n'
a = ones((3,4))*4
print a, '\n'
c = array([1,1,1])
b = c_[a,c]
print b, '\n\n'
a = ones((4,3))*4
print a, '\n'
c = array([[1,1,1]])
b = r_[a,c]
print b
print type(vector_b)
# we'll utilize the concept of unpackingIn[15]:(*a,*b)Out[15]:(1,2,3,5,6)# using `numpy.ravel()`In[14]: np.ravel((*a,*b))Out[14]: array([1,2,3,5,6])# wrap the unpacked elements in `numpy.array()`In[16]: np.array((*a,*b))Out[16]: array([1,2,3,5,6])
>>> a = np.array([[1,2],[3,4]])>>> b = np.array([[5,6]])# Appending below last row>>> np.concatenate((a, b), axis=0)
array([[1,2],[3,4],[5,6]])# Appending after last column>>> np.concatenate((a, b.T), axis=1)# Notice the transpose
array([[1,2,5],[3,4,6]])# Flattening the final array>>> np.concatenate((a, b), axis=None)
array([1,2,3,4,5,6])