Concatenation And Splitting

1. CONCATENATING ARRAYS

np.concatenate() constructor is used to concatenate or join two or more arrays into one. The only required argument is list or tuple of arrays.

πŸ’‘For np.concatenate() to work, all the input array dimensions for the concatenation axis must match exactly, other wise you will get ValueError

1.1. 1D arrays

Let’s get straight to work and define two arrays and then join them:

# first, import numpy
import numpy as np

# making two arrays to concatenate
arr1 = np.arange(1,4)
arr2 = np.arange(4,7)

print("Arrays to concatenate:")
print(arr1);print(arr2)

print("After concatenation:")
print(np.concatenate([arr1,arr2]))
Arrays to concatenate:
[1 2 3]
[4 5 6]
After concatenation:
[1 2 3 4 5 6]

We can also join more than two arrays:

1.2. nD arrays

The same constructor is used for joining two or more nD arrays

By default, np.concat joins along the row wise (stack on top of each other). However, by providing kwarg axis=1, we can also concatenate along columns.

2. CONCATENATING ARRAYS OF MIXED DIMENSIONS

To concatenate arrays of mixed dimensions we will use np.vstack and np.hstack functions

2.1. Vertical Stack ( np.vstack)

np.vstack concatenate along rows, stack vertically.

πŸ’‘ To make vstack work, all input arrays should have same number of columns

2.1. Horizontal Stack ( np.hstack)

np.hstack concatenate along columns, stack one after the other.

πŸ’‘To make hstack work, both arrays should have same number of rows

np.dstack is used for stacking 3 arrays

3. SPLITTING

Opposite of concatenation is splitting and we will use np.split, np.vsplit and np.hsplit to split the arrays

3.1. np.split

np.split for N split points creates N+1, sub-arrays np.split(x,y) will split the array into three subarray. An example will make the concept clearer:

3.2… np.vsplit

np.vsplit splits along the vertical axis. You can either provide:

  • integer of equally shaped array (method 1 below), or,

  • by specifying the row [integer] at which the division should occur (method 2 below)

3.3. np.hsplit

np.hsplit splits along the horizontal axis. You can either provide:

  • number integer of equally shaped array, or,

  • by specifying the column [integer] at which the division should occur

Last updated