Basic slicing and advanced indexing in NumPy Python

NumPy or Numeric Python — it is a package for computations on homogeneous n-dimensional arrays. In awesome dimensions, they are called axes.

Why do we need NumPy?

The question arises, why do we need NumPy when Python lists are already there. The answer to this is that we cannot operate on all the elements of the two lists directly. For example, we cannot multiply two lists directly, we have to do it element by element. This is where the NumPy role comes into play.

Output:

 TypeError: can`t multiply sequence by non-int of type `list`  

Where is it easy to do with NumPy arrays. 
Another example,

# Python program to demonstrate the need for NumPy

  

list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ]

list2 = [ 10 , 9 , 8 , 7 , 6 , 5 ]

 
# Multiplying both lists directly will result in an error.

print (list1 * list2)

# Python program to demonstrate using NumPy arrays

import numpy as np

  

list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ]

list2 = [ 10 , 9 8 , 7 , 6 , 5 ]

  
# Convert list1 to a NumPy array

a1 = np.array (list1)

 
# Convert list2 to NumPy array

a2 = np.array (list2)

 

print (a1 * a2)

Output:

 array ([10, 18, 24, 28, 30, 30])  

This article will help you familiarize yourself with indexing in NumPy in detail. The Python numpy package has a lot of indexing power in various ways.

Indexing using array indexes

Indexing can be done using an array as an index. In the case of a slice, a view or shallow copy of the array is returned, but a copy of the original array is returned in the index array. Numpy arrays can be indexed with other arrays or any other sequence except tuples. The last element is indexed by -1 second, the last by -2, and so on.

# Python program for demonstration
# using index arrays.

import numpy as np

 
# Create a sequence of integers from 10 to 1 in increments of -2

a = np.arange ( 10 , 1 , - 2

print ( " A sequential array with a negative step: " , a)

 
# Indexes are specified inside method np.array.

newarr = a [np.array ([ 3 , 1 , 2 ])]

print ( "Elements at these indices are:" , newarr)

Exit:

 A sequential array with a negative step: [10 8 6 4 2] Elements at these indices are: [4 8 6] 

Another example,

import numpy as np

 
# NumPy array with elements from 1 to 9

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

 
# Index values ​​can be negative.

arr = x [np.array ([ 1 , 3 , - 3 ])]

print ( "Elements are:" , arr)

Output:

 Elements are: [2 4 7] 

Indexing types

There are two types of indexing:

  1. Basic slicing and indexing: consider the syntax x [obj], where x — an array, and obj — index. Slice object is the index in case of basic slicing. Basic slicing occurs when an object:
    1. a slice object of the form start: stop: step
    2. an integer
    3. or a tuple of slice objects and integers

    All arrays generated by the base section always match the original array.

    # Python program for basic slicing.

    import numpy as np

     
    # Arrange items 0 to 19

    a = np.arange ( 20 )

    print ( "Array is:" , a)

      # a [start: stop: step]

    print ( "a [-8: 17: 1] =" , a [ - 8 : 17 : 1 ]) 

     
    # Operator: means all elements to the end.

    print ( "a [10:] =" , a [ 10 :])

    Output:

     Array is: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] a [-8: 17: 1] = [12 13 14 15 16] a [10:] = [10 11 12 13 14 15 16 17 18 19] 

    The ellipsis can also be used alongside from the main cutting. Ellipsis (...) — this is the number of objects required to create a selection tuple of the same length as the array.

    Output:

     [[2 5] [8 11]] 
  2. Extended indexing: Extended indexing is triggered when obj:
    1. ndarray of type integer or Boolean
    2. or a tuple with at least one sequence object
    3. is a non-tuple sequence object

    Expanded I indexing returns a copy of the data, not a scan. Extended indexing comes in two types: integer and boolean.

    Pure integer indexing: when integers are used for indexing. Each element of the first dimension is connected to an element of the second dimension. So the index of the items in this case is (0,0), (1,0), (2,1) and the corresponding items are selected.

  3. # Python program for indexing using base ellipsis slices

    import numpy as np

     
    # Three-dimensional array.

    b = np.array ([[[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]],

    < code class = "plain"> [[ 7 , 8 , 9 ], [ 10 , 11 , 12 ]]])

      

    print (b [..., 1 ]) # Equivalent to b [:,:, 1]

    # Program Python showing advanced indexing

    import numpy as np

     

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

    print (a [[ 0 1 , 2 ], [ 0 , 0 , 1 ]])

    Output:

     [1 3 6] 

    Boolean indexing
    This indexing has some boolean expression as an index. Items that match this boolean expression are returned. Used to filter the values ​​of the desired elements.

    # You can choose numbers greater than 50

    import numpy as np

     

    a = np.array ([ 10 , 40 , 80 , 50 , 100 ])

    print (a [a & gt; 50 ])

    Output:

     [80 100]  

     

    # You may want to square multiples of 40

    import numpy as np

      

    a = np.array ([ 10 , 40 , 80 , 50 , 100 ])

    print (a [a % 40 = = 0 ] * * 2 )

    Output:

     [1600 6400]) 

    # You can select those elements whose
    # the line sum is a multiple of 10.

    import numpy as np

     

    b = np.array ([[ 5 , 5 ], [ 4 , 5 ], [ 16 , 4 ]])

    sumrow = b. sum ( - 1 )

    print (b [sumrow % 10 = = 0 ])

    Output:

     array ([[5, 5], [16, 4]]) 

Link:
SciPy.org

This article is provided by Ayushi Astana . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.