Indexing And Slicing In Numpy Array.


Indexing And Slicing In Numpy Array.

Table Of Contents:

  1. Numpy Indexing
  2. Numpy Slicing

(1) Numpy Indexing

Syntax:

array[start:end:steps]

Parameters:

  1. Start: Starting position of the element
  2. End: Ending Position Of The Element
  3. Steps: Number Of Steps To Jump While Travelling.

Example-1:

data = np.array([1, 2, 3])
data
array([1, 2, 3])
data[0]
1

Note:

  • It will select the value at index position ‘0’ which is ‘1’.

Example-2:

data[0:2]
array([1, 2])

Note:

  • It will select the value from ‘0’ to (end_index -1)  = (2 – 1)  = 1.

Example-3:

data[1:]
array([2, 3])

Note:

  • Here start index is ‘1’ and we did not mention the end index, hence default will be the last index value.

Example-4:

data[-2:]
array([2, 3])

Note:

  • If we have a negative sign, it will travel from back to front.
  • The last element index will be ‘-1’.

(2) Numpy Slicing

  • You may want to take a section of your array or specific array elements to use in further analysis or additional operations.
  • To do that, you’ll need to subset, slice, and/or index your arrays.
  • If you want to select values from your array that fulfil certain conditions, it’s straightforward with NumPy.

Example-1:Numbers That Are Less Than 6.

a = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
print(a[a < 6])

Output:

[1 2 3 4 5]

Example-2:Numbers that are equal to or greater than 5

five_up = (a >= 5)
print(a[five_up])

Output:

[ 5  6  7  8  9 10 11 12]

Example-3: You can select elements that are divisible by 2:

divisible_by_2 = a[a%2==0]
print(divisible_by_2)

Output:

[ 2  4  6  8 10 12]

Example-4: Using Conditional Operator

c = a[(a > 2) & (a < 11)]
print(c)

Output:

[ 3  4  5  6  7  8  9 10]

Example-5: Using Logical Operator

five_up = (a > 5) | (a == 5)
print(five_up)

Output:

[[False False False False]
 [ True  True  True  True]
 [ True  True  True  True]]

Note:

  • You can also make use of the logical operators & and | in order to return boolean values that specify whether or not the values in an array fulfil a certain condition
  • This can be useful with arrays that contain names or other categorical values.

Leave a Reply

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