## Python Programming – Joining And Splitting

Joining(concatenation) of arrays means combining multiple arrays into one and splitting of arrays means splitting one array into many. Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines np. concatenate, np.stack, and np.stack. np. concatenate takes a tuple or list of arrays as its first argument.

**Example**

Demo of concatenation.

# Concatenation import numpy as np x = np.array([1, 2, 3]) y = np.array([5, 6, 7]) z=np.concatenate([x, y]) print(z)RUN >>> [1 2 3 5 6 7] >>> |

You can also concatenate more than two arrays at once. In addition to the concatenation function, Numpy also offers two convenient functions stack(horizontal stack) and stack(vertical stack) which allows you to concatenate two multi-dimensional arrays vertically or horizontally. (See Figure 13.24).

**Example**

Demo of vstack and hstack functions.

import numpy as np a = np.array([[1,2,30], [10,15,4]]) b = np.array([[1,2,3], 112, 19, 29]]) print(“Arrays vertically concatenated\n”,np.vstack((a,b))) print(“Arrays horizontally concatenated\n”,np.hstack((a,b)))RUN >>> Arrays vertically concatenated [ [ 1 2 30] [10 15 4] [12 3] [12 19 29] ] Arrays horizontally concatenated [ [ 1 2 30 1 2 3] [1015 4 12 19 29]] >>> |

**Let’s Try**

import numpy as np a = np.array([[1,2,3],[11,12,13]]) b = np.array([[4,5,6], [14, 15, 16]]) print(“Arrays vertically concatenated\n”,np.vstack((a,b))) print(“Arrays horizontally concatenated\n”,np.hstack((a,b))) |

The opposite of concatenation is splitting, i.e., to split a single array into multiple arrays which is implemented by the functions np.split, np.hsplit,and np.vsplit. For each of these, you can pass a list of indices giving the split points. (See Figure 13.25).

**Example**

Demo of splitting.

# Splitting import numpy as np x = [1, 2, 3 , 99, 99, 3, 2, 1] xl, x2. x3 = np.split (x. [3, 5]) print(x1, x2 , x3)RUN >>> [1 2 3] [99 99] [3 2 1] >>> |

**Let’s Try**

# Splitting import numpy as np x = [1, 2, 3, 4, 5, 6, 7, 8] x1, x2, x3 = np.split(x. [2, 4]) print(x1, x2. x3) |