Python slice array without numpy

Numpy makes the vertical slicing of 2 dimensional array easier. However, you can achieve the same results without it. Imagine if we have the following 2D list:

arr1=[[1,1,1,0,0,0],[0,1,0,0,0,0],[1,1,1,0,0,0],[0,0,2,4,4,0],[0,0,0,2,0,0],[0,0,1,2,4,0]]

which is represented as the following matrix:

[[1, 1, 1, 0, 0, 0],
 [0, 1, 0, 0, 0, 0],
 [1, 1, 1, 0, 0, 0],
 [0, 0, 2, 4, 4, 0],
 [0, 0, 0, 2, 0, 0],
 [0, 0, 1, 2, 4, 0]]

Let's say that you want to slice this to form the pattern below :

Python slice array without numpy

This can be achieved without numpy by the following :

for x in range (0,4):
        for y in range (0,4):
            # Here we traverse through the 2D array vertically
            temp_matrix= arr1[x][y:y+3],arr1[x+1][y:y+3],arr1[x+2][y:y+3]
             print (temp_matrix) 

If we use numpy instead we can re-write the following code :

arr=np.array(arr1)
rows = arr.shape[0]
cols = arr.shape[1]
for x in range (0,rows-2):
    for y in range (0, cols-2):
        print(arr[x:x+3,y:y+3])

Numpy makes the vertical slicing of 2 anycodings_numpy dimensional array easier. However, you anycodings_numpy can achieve the same results without it. anycodings_numpy Imagine if we have the following 2D anycodings_numpy list:

arr1=[[1,1,1,0,0,0],[0,1,0,0,0,0],[1,1,1,0,0,0],[0,0,2,4,4,0],[0,0,0,2,0,0],[0,0,1,2,4,0]]

which is represented as the following anycodings_numpy matrix:

[[1, 1, 1, 0, 0, 0],
 [0, 1, 0, 0, 0, 0],
 [1, 1, 1, 0, 0, 0],
 [0, 0, 2, 4, 4, 0],
 [0, 0, 0, 2, 0, 0],
 [0, 0, 1, 2, 4, 0]]

Let's say that you want to slice this to anycodings_numpy form the pattern below :

This can be achieved without numpy by anycodings_numpy the following :

for x in range (0,4):
        for y in range (0,4):
            # Here we traverse through the 2D array vertically
            temp_matrix= arr1[x][y:y+3],arr1[x+1][y:y+3],arr1[x+2][y:y+3]
             print (temp_matrix) 

If we use numpy instead we can re-write anycodings_numpy the following code :

arr=np.array(arr1)
rows = arr.shape[0]
cols = arr.shape[1]
for x in range (0,rows-2):
    for y in range (0, cols-2):
        print(arr[x:x+3,y:y+3])

Slicing NumPy Arrays like an expert

The ultimate numpy array indexing and slicing guide

Photo by Daniel Lincoln on Unsplash

Intro

Slicing numpy arrays is like peeling fruits. You cut a part away and keep the rest. — The numpy ninja —

After reading this post you should be able to slice through arrays like through butter. I will start out by explaining how to select a single element from a numpy array. Then I will show you how to slice a 1 dimensional array. I will build up more dimensions, until you should be able to slice arrays with any number of dimensions. Towards the end of the article, I want to show you that mixing single indexes and slicing reduces the number of dimension of the slicing result.

Select a single element

One dimensional array

The indexes of a one dimensional numpy array start at 0. This means that the first element would have the index 0. The second element would have the index 1, the third element the index 2 and so on.

Python slice array without numpy

(Image by author)

Let’s say, I want to print the number 7 (which is the second element). I get it by indexing the array “arr” with a 1 in square brackets.

Python slice array without numpy

Two dimensional arrays

To get a single element from a 2 dimensional array, I have to provide two indexes.

Python slice array without numpy

(Image by author)

The first index is always along the axis surrounded by the least amount of brackets.

To get for example the number 5 from this array, you would have to index the array with the first and then the second index.

Python slice array without numpy

(Image by author)

If think of 2D arrays organized in columns, you can think of the first index selecting the row and the second index selecting the column.

Python slice array without numpy

(Image by author)

Three or more dimensional arrays

For three or more dimensional arrays, you have to provide one index for each dimension.

Python slice array without numpy

(Image by author)

The first index always selects the element inside the most outer square brackets. By this logic you can figure out the order of indexes in any arbitrary array.

Let’s say I want to retrieve the number 10 from this array. In thought, start with the full array and select the part containing the number you want, throwing away the rest.

Python slice array without numpy

(Image by author)

So to print the number 10 in this array, I would use the indexes 1,2,0.

Python slice array without numpy

(Image by author)

Counting backwards with negative indexes

You can provide negative Indexes to count backwards in the array. The index of the last index is -1, the index of the second last element is -2 and so on.

One dimensional

Python slice array without numpy

(Image by author)

Two dimensional

Python slice array without numpy

(Image by author)

Three dimensional

Python slice array without numpy

(Image by author)

Combining positive and negative indexes

You can always combine positive and negative indexes to select an element in an array. For example if I want to print the number 5 from the following array, I can index it with -2 as first index and 2 as second index.

Python slice array without numpy

(Image by author)

Select a part of an array (= slicing)

To select only a part of an array is called slicing.

One dimensional array

Python slice array without numpy

(Image by author)

To slice a one dimensional array, I provide a start and an end number separated by a semicolon (:). The range then starts at the start number and one before the end number.

Python slice array without numpy

(Image by author)

When I want to get the whole array from the start until the element with index 3, I could write: print(arr[0:4]). However this is the same as:

Python slice array without numpy

(Image by author)

Similarly, to get from the index 1 all the way to the end of the array, I can write it without providing a slicing end.

Python slice array without numpy

(Image by author)

To print the full array, I index with a colon only.

Python slice array without numpy

(Image by author)

For 1 dimensional arrays, it does not make sense to print the whole array in this fashion, but rather to print the array directly by using: print(arr). However, when you slice an array, it get’s copied. This is not the case when you use the original array without slicing. For an application like printing this difference does not matter, but for other cases, where an array get’s modified, it can matter.

Two dimensional arrays

When I slice a 2D array, I imagine that the result is the intersection between the selected rows (first index) and columns(second index).

Python slice array without numpy

(Image by author)

When I give only the first index to a 2D array, it gives me back a whole row. For example print(arr[1,:]) would be the same as print(arr[1]).

Python slice array without numpy

(Image by author)

Three or more dimensional arrays

Slicing for three or more dimensional arrays follows the same logic as for 2D arrays, but I cannot imagine it in terms of rows and columns.

Python slice array without numpy

(Image by author)

I think of slicing 3D or more dimensional arrays in the following fashion. I start at the most outer brackets and select from start to end according to the first indexes. Then I go a level of brackets deeper and select from start to end according to the second indexes.

Python slice array without numpy

(Image by author)

Slicing with negative indexes

When slicing with negative indexes, the slice starts at the start and ends one element before the end, like with positive indexes. So for example if I want to print(arr[-4:-1]) the last element to be printed has index -2.

Python slice array without numpy

(Image by author)

Combining slicing and single indexes

Please note, that when you use single indexes and slicing at the same time, you loose dimensions. More specifically, you loose the dimension where you use the single index. Let’s consider the following example:

Python slice array without numpy

(Image by author)

The third dimension will be reduced. It makes sense because, the brackets surrounding the most inner segments are not needed for only one element and numpy will remove them. The resulting array will be 2D.

Python slice array without numpy

(Image by author)

You can always use a negative index as start and a positive as end. However ensure that the element at the start index must be to the left of the element with the end index. Otherwise you will get an empty array back.

Summary

The key takeaways you should have after reading this post should be.

  • The indexes of an array start with 0.
  • If you want to get a single number from an array, you have to give as many indexes as the array has dimensions.
  • You slice an array by giving a start and an end index separated by a colon (:). You will get the elements form the start index to one element before the end index
  • To slice from the start you simply don’t specify a start. To slice from the end you simply don’t specify an end. If you want every element in a dimension, you give neither start nor end and simply write a colon(:)
  • When slicing a 2D array, you can imagine the result as the intersection of the selected rows and the selected columns.

Want to connect and support me?

Linkedin
https://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/
Facebook
https://www.facebook.com/profile.php?id=100072095823739
Twitter
https://twitter.com/Vincent02770108
Medium
https://medium.com/@Vincent.Mueller
Become medium member and support me (part of your membership fees go directly to me)
https://medium.com/@Vincent.Mueller/membership

Can you slice an array in Python?

Python has an amazing feature just for that called slicing. Slicing can not only be used for lists, tuples or arrays, but custom data structures as well, with the slice object, which will be used later on in this article.

How do you slice a 2d list in Python?

As shown in the above syntax, to slice a Python list, you have to append square brackets in front of the list name. Inside square brackets you have to specify the index of the item where you want to start slicing your list and the index + 1 for the item where you want to end slicing.

How do you slice a list in Python?

The format for list slicing is [start:stop:step]. start is the index of the list where slicing starts. stop is the index of the list where slicing ends. step allows you to select nth item within the range start to stop.

What is Numpy slicing in Python?

Numpy with Python Basic slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array.