Part 2 : NumPy Slicing and Stacking Arrays

If you don’t know what is NumPy array then please visit first our post NumPy Basic Array Operations. In this post we will continue our numpy course. In this post we will learn slicing and indexing, iterating, stacking and splitting array.

1. Slicing Array

Slicing in Python is the process of moving elements from one index to another.

Syntax : [start:end:step]
Single Dimension Array
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7])
>>> print(a[1:5])
[2 3 4 5]

In this example you can see it’s print a elements by index(1) to index(5). In array indexing start with zero (0).

>>> a = np.array([1, 2, 3, 4, 5, 6, 7])
>>> a[-1] 
7  

Here -1 point to the last element of the array.

Multidimensional Arrays
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) 
>>> a
array([[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]])
>>> a[1,2] 
6   

In this example you can see it point to that element which has row indexing with 1 and column indexing with 2

>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> a[0:2,2] 
array([3, 6])

In this example print 2nd element of each row within continue loop but only for 2 steps.

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) 
>>> a
array([[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]])
>>> a[-1] 
array([7, 8, 9])

In this example to print last row of the multidimensional array we have to use -1 as index.

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) 
>>> a
array([[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]])
>>> a[-1, 0:2] 
array([7, 8])

In this example first it is fetch last row which is [7, 8, 9] after from this row print element which index is a[0] and a[1] within continue loop but only for 2 steps.

If you want print only two column and skip first column the syntax will be like this:

>>> a
array([[1, 2, 3], 
       [4, 5, 6], 
       [7, 8, 9]])
>>> a[:,1:3] 
array([[2, 3], 
       [5, 6], 
       [8, 9]])

Explanation : In this example the first parameter : , for go through all rows and second parameter 1:3 , for print all element which is lie in index a[1] to a[2].

2. Iterating Array

to print all rows from array using for loop:

>>> for row in a:
...     print(row)
... 
[1 2 3]
[4 5 6]
[7 8 9]

falt : falt property used to print element in array to a single dimension.

>>> for cell in a.flat:
...     print(cell)
... 
1
2
3
4
5
6
7
8
9

nditer() : The function nditer() is a helping function that can be used from very basic to very advanced iterations

Without nditer():

>>> b= np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> for row in b:
...     print(row)
... 
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]

With nditer():

>>> for row in np.nditer(b):
...     print(row)
... 
1
2
3
4
5
6
7
8

3. Stacking Array

To combine a succession of same-dimension arrays along a new axis, use the numpy.stack() function. The axis parameter defines the new axis’ index in the result’s dimensions.

Let we have these 2 array:

>>> a1 = np.arange(6).reshape(3,2)
>>> a1
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> a2 = np.arange(6,12).reshape(3,2)
>>> a2
array([[ 6,  7],
       [ 8,  9],
       [10, 11]])

Using stack() combine these array:

>>> np.stack((a1,a2))       
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]]])

We pass a sequence of arrays that we want to join to the stack() method along with the axis.

>>> np.stack((a1,a2),axis=1) 
array([[[ 0,  1],
        [ 6,  7]],

       [[ 2,  3],
        [ 8,  9]],

       [[ 4,  5],
        [10, 11]]])

Vertical stacking : combine 2 array in vertical manner.

>>> np.vstack((a1,a2)) 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

Horizontal stacking : combine 2 array in horizontal manner.

>>> np.hstack((a1,a2)) 
array([[ 0,  1,  6,  7],
       [ 2,  3,  8,  9],
       [ 4,  5, 10, 11]])

4. Splitting Array

Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple.

>>> arr = np.array([1, 2, 3, 4, 5, 6])
>>> np.array_split(arr, 3)
[array([1, 2]), array([3, 4]), array([5, 6])]

Get data from spitted array:

>>> res = np.array_split(arr,3)
>>> res[0] 
array([1, 2])

There is some other function that can use to split arrays. Let apply those function with multidimensional array.

>>> x = np.arange(16).reshape(4, 4) 
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

hsplit(): Splits an array into multiple sub-arrays horizontally (column-wise).

>>> np.hsplit(x,2) 
[array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]])]

vsplit(): It Split array into multiple sub-arrays vertically (row wise).

>>> np.vsplit(x,2)
[array([[0, 1, 2, 3],
       [4, 5, 6, 7]]), array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])]

That is it for today, This is final part of our NumPy course, hope it helps. If you have any suggestion for this article please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

Part 2 : NumPy Slicing and Stacking Arrays

One thought on “Part 2 : NumPy Slicing and Stacking Arrays

  1. Hey there, You have done a great job. I will certainly digg it and for my part recommend to my friends. I am confident they will be benefited from this website.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top