See also

Joining arrays

Another way to create new arrays is to join, or concatenate, other arrays. There are several functions that make that easy. One common task is to create a two-dimensional array from its columns, and NumPy provides the column_stack() function for this specific purpose, as shown in the following example:

x = np.array([1,2,3])
y = np.array([4,5,6])
z = np.array([7,8,9])
w = np.column_stack([x,y,z])

This produces the array:

array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Notice that the arrays x, y, and z are interpreted as column vectors. The columns_stack() function always interprets its arguments as column arrays.

The concatenate() function is used to stack arrays along an arbitrary axis. The following example shows the concatenation of two arrays along axis 0:

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[10,20,30],[40,50,60],[70,80,90]])
z = np.concatenate([x,y])

With this code, the arrays x and y are stacked vertically, generating the following array:

array([[ 1,  2,  3],
[ 4, 5, 6],
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])

Notice that, when using concatenate(), all input arrays must have the same dimension, except possibly for the axis along which they are being stacked. The following code shows how to concatenate two arrays side by side:

x = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
y = np.array([[10,20],[30,40]])
z = np.concatenate([x,y], axis=1)

The output will now be as follows:

array([[ 1,  2,  3,  4, 10, 20],
[ 5, 6, 7, 8, 30, 40]])

The preceding examples of concatenate() represent the usual cases, that is, concatenating two-dimensional arrays along either axis 0 or axis 1. In these specific cases, NumPy has the convenient vstack() and hstack() functions. Thus, an alternative to stacking two arrays vertically is indicated in the following code:

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[10,20,30],[40,50,60],[70,80,90]])
z = np.vstack([x,y])

Analogously, we can stack two arrays horizontally with the code:

x = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
y = np.array([[10,20],[30,40]])
z = np.hstack([x,y])

If we want to add elements at the end of an array, we can use the append() function. The following code example shows how to add a row at the bottom of an array:

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[7,8,9]])
z = np.append(x, y , axis=0)

Notice that in the call to append(), we specifically state the concatenation axis with the axis=0 option. If the axis is not specified, append() will flatten the output array, which is not normally what is wanted. Also, notice that the y array is defined with the np.array([[7,8,9]]) expression, which is a 1 x 3 array. The code would not work if y were defined with np.array([7,8,9]), which does not match the shape of array x.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset