Accessing Elements of ndarray
- Indexin⇒ only one element.
- Slicing ⇒ group of elements which are in order.
- Advanced indexing ⇒ group of elements which are not in order(arbitrary elements).
- Condition based selection ⇒ array_name[conditi.
Indexing — only one element
- By using index, we can get/access single element of the array.
- Zero Based indexing. Ie the index of first element is 0.
- supports both +ve and -ve indexing.
Accessing elements of 1-D array
- 1-D array : array[index].
Syntax
- 1-D array :array[index].
- D array :array[row_index][column_index].
- D array :array[2-D array index][row_index_in that 2-D array][columnindex in that.d array].
Example
# 1-D array
# array[index]
import numpy as np
a = np.array([10,20,30,40,50])
a[3]
output
40
Example
# -ve indexing
a[-1]
Output
50
Accessing elements of 2-D array
- 2-D array ⇒ Collection of 1-D arrays.
- There are 2 axis are present in 2-D array.
axis-0 :: row index.
axis-1 :: column index.
- 2-D array : array[row_index][column_index].

Example
# 2-D array
# a[rowindex][columnindex]
import numpy as np
a = np.array([[10,20,30],[40,50,60]])
print(f"Shape of the array a : {a.shape}")
print("To Access the element 50")
print(f"a[1][1] ⇒ {a[1][1]}")
print(f"a[1][-2] ⇒ {a[1][-2]}")
print(f"a[-1][2] ⇒ {a[-1][-2]}")
print(f"a[-1][1] ⇒ {a[-1][1]}")
Output
Shape of the array a : (2, 3)
To Access the element 50
a[1][1] ⇒ 50
a[1][-2] ⇒ 50
a[-1][2] ⇒ 50
a[-1][1] ⇒ 50
Accessing elements of 3-D array
- 3-D arrays ⇒ Collection of 2-D arrays.
- There are 3 index in 3-D array.
axis-0 :: No of 2-D arrays.
axis-1 :: Row index.
axis-2 :: column index.
- 3-D array : array[2-D array index][row_index_in that 2-D array][columnindex in that 2-d array].
a[i][j][k]
- i ⇒ represents which 2-D array(index of 2-D array) | can be either +ve or -ve.
- j ⇒ represents row index in that 2-D array | can be either +ve or -ve.
- k ⇒ represents column index in that 2-D array | can be either +ve or -ve.
Eg: a[0][1][2]
- 0 indexed 2-D array.
- In that 2-D array row-index 1 and column-index 2 will be selected.
# 3-D array
# array[2-D array index][row_index in that 2-D array][column_index in that 2-D
array]

Example
import numpy as np
l = [[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]]
a = np.array(l)
print(f"Shape of the array a ⇒ {a.shape}")
print("To access the element 14 from the 3-D array")
print(f"a[1][1][1] ⇒ {a[1][1][1]}")
print(f"a[-1][-2][-2] ⇒ {a[-1][-2][-2]}")
print(f"a[1][-2][-2] ⇒ {a[1][-2][-2]}")
print(f"a[-1][1][-2] ⇒ {a[-1][1][-2]}")
Output
Shape of the array a ⇒ (2, 3, 3)
To access the element 14 from the 3-D array
a[1][1][1] ⇒ 14
a[-1][-2][-2] ⇒ 14
a[1][-2][-2] ⇒ 14
a[-1][1][-2] ⇒ 14
Accessing elements of 4-D array
- 4-D array contains multiple 3-D arrays.
- Every 3-D array contains multiple 2-D arrays.
- Every 2-D array contains rows and columns.
(i,j,k,l) ⇒ (2,3,4,5)
- 2 ⇒ represents the number of 3-D arrays.
- 3 ⇒ Every 3-D array contains 3 2-D arrays.
- Every 2-D array contains 4 rows and 5 columns.

Example
# 4-D array
import numpy as np
a = np.arange(1,121).reshape(2,3,4,5)
print(f"Size of the array ⇒ {a.size}")
print(f"Shape of the array ⇒ {a.shape}")
print(f"a ⇒\n {a}")
Output
Size of the array ⇒ 120
Shape of the array ⇒ (2, 3, 4, 5)
a ⇒
[[[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[ 11 12 13 14 15]
[ 16 17 18 19 20]]
[[ 21 22 23 24 25]
[ 26 27 28 29 30]
[ 31 32 33 34 34 35]
[36 37 38 39 40]]
[[ 41 42 43 44 45]
[ 46 47 48 49 50]
[ 51 52 53 54 55]
[ 56 57 58 59 60]]]
[[[ 61 62 63 64 65]
[ 66 67 68 69 70]
[ 71 72 73 74 75]
[ 76 77 78 79 80]]
[[ 81 82 83 84 85]
[ 86 87 88 89 90]
[ 91 92 93 94 95]
[ 96 97 98 99 100]]
[[101 102 103 104 105]
[106 107 108 109 110]
[111 112 113 114 115]
[116 117 118 119 200]]]]
Example
# to know the position of an element in the array
np.where(a==88)
output
(array([1], dtype=int64),
array([1], dtype=int64),
array([1], dtype=int64),
array([2], dtype=int64))
Example
# accessing the element at a[1][1][1][2]
print(f"The element present at a[1][1][1][2] ⇒ {a[1][1][1][2]}")
output
The element present at a[1][1][1][2] ⇒ 88
Slicing ⇒ group of elements which are in order Python’s slice operator:
Syntax-1: l[begin:end].
- It returns elements from begin index to (end-1) index.

l = [10,20,30,40,50,60,70]
l[2:6] #from 2nd index to 5th index
Output
[30, 40, 50, 60]
Example
l[-6:-2] #From -6 index to -3 index
Output
[20, 30, 40, 50]
Example
# If we are not specifying begin index then default is 0
l[:3] #from 0 index to 2nd index
Output
[10, 20, 30]
Example
# If we are not specifying end index then default is upto last
l[2:] # from 2nd index to last
Output
[30, 40, 50, 60, 70]
Example
# if we are not specifying begin and end then it will considered all elements
l[:] # it is equivalent to l
Output
[10, 20, 30, 40, 50, 60, 70]
Syntax-2: l[begin:end:step].
- begin,end and step values can be either +ve or -ve. These are optional.
- If begin is not specified then 0 will be taken by default.
- If end is not specified then upto end of the list will be taken.
- If step is not specified then 1 will be taken by default. Step value cannot be 0.
- If step value is +ve, then in forward direction begin to end-1 will be considered.
- If step value is -ve, then in backward direction begin to end+1 will be considered.
- In forward direction, if end is 0 then the result will be always empty.
- In backward direction, if end is -1 then the result will be always empty.
Note:
- slice operator does not raise any IndexError when the index in out of range.
Example
# slice operator in python list
l = [10,20,30,40,50,60,70,80,90]
l[2:6:2] # from 2nd index to 6-1 index with step 2
Output
[30, 50]
Slice operator on 1-D numpy array
same rules of python slice operator.
Syntax: array_name[begin:end:step].
- begin,end and step values can be either +ve or -ve. These are optional.
- If begin is not specified then 0 will be taken by default.
- If end is not specified then upto end of the list will be taken.
- If step is not specified then 1 will be taken by default. step value cannot be 0.
- If step value is +ve, then in forward direction begin to end-1 will be considered.
- If step value is -ve, then in backward direction begin to end+1 will be considered.
- In forward direction, if end is 0 then the result will be always empty.
- In backward direction, if end is -1 then the result will be always empty.
Example
# Slice operator on 1-D array
import numpy as np
a = np.arange(10,101,10)
Output
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
Example
a[2:5] # from 2nd index to 5-1 index
Output
array([30, 40, 50])
Example
a[::1] # entire array
Output
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
Example
a[::-1] # entire array in reverse order
Output
array([100, 90, 80, 70, 60, 50, 40, 30, 20, 10])
Slice operator on 2-D numpy array
Syntax
- array_name[row,column].
- array_name[begin:end:step,begin:end:step].

Example
# slice operator on 2-D array
a = np.array([[10,20],[30,40],[50,60]])
a
Output
array([[10, 20],
[30, 40],
[50, 60]])
Note
- row and colum should be in slice syntax then only it will return 2-D array.
- If any one is index then it will return 1-D array.
Example
import numpy as np
a = np.array([[10,20],[30,40],[50,60]])
b = a[0,:] # row is in index form, it will return 1-D array
c = a[0:1,:] # it will return 2-D array
print(f"The dimension of b : {b.ndim} and the array b : {b} ")
print(f"The dimension of c : {c.ndim} and the array c : {c} ")
Output
The dimension of b : 1 and the array b : [10 20]
The dimension of c : 2 and the array c : [[10 20]]
Example
print(f"a[0:2,1:2] value is : \n {a[0:2,1:2]}")
print(f"a[:2,1:] value is : \n {a[:2,1:]}")
Output
a[0:2,1:2] value is :
[[20]
[40]]
a[:2,1:] value is :
[[20]
[40]]
Example
print(f"a[0::2,:] value is : \n {a[0::2,:]}")
print(f"a[::2,:] value is : \n {a[::2,:]}")
Output
a[0::2,:] value is :
[[10 20]
[50 60]]

Example
# 4 X 4 array
a = np.arange(1,17).reshape(4,4)
a
Output
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
Example
print(f"a[0:2,:] value is : \n {a[0:2,:]}")
print(f"a[0::3,:] value is : \n {a[0::3,:]}")
print(f"a[:,:2] value is : \n {a[:,:2]}")
print(f"a[:,::2] value is : \n {a[:,::2]}")
print(f"a[1:3,1:3] value is : \n {a[1:3,1:3]}")
print(f"a[::3,::3] value is : \n {a[::3,::3]}"
Output
a[0:2,:] value is :
[[1 2 3 4]
[5 6 7 8]]
a[0::3,:] value is :
[[ 1 2 3 4]
[13 14 15 16]]
a[:,:2] value is :
[[ 1 2]
[ 5 6]
[ 9 10]
[13 14]]
a[:,::2] value is :
[[ 1 3]
[ 5 7]
[ 9 11]
[13 15]]
a[1:3,1:3] value is :
[[ 6 7]
[10 11]]
a[::3,::3] value is :
[[ 1 4]
[13 16]]
Slice operator on 3-D numpy array
Syntax
array_name[i,j,k].
- i ⇒ indices of 2-D array (axis-0).
- j ⇒ row index (axis-1).
- k ⇒ column index (axis-2).

Example
# slice operator on 3-D array
import numpy as np
a = np.arange(1,25).reshape(2,3,4)
a
Output
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
Example
print(f"The slice of a[:,:,:1] :\n {a[:,:,:1]}")
Output
The slice of a[:,:,:1] :
[[[ 1]
[ 5]
[ 9]]
[[13]
[17]
[21]]]
Example
print(f"The slice of a[:,:1,:] ⇒ \n {a[:,:1,:]}")
Output
The slice of a[:,:1,:] ⇒
[[[ 1 2 3 4]]
[[13 14 15 16]]]
Example
print(f"The slice of a[:,::2,:] ⇒ \n {a[:,::2,:]}")
Output
The slice of a[:,::2,:] ⇒
[[[ 1 2 3 4]
[ 9 10 11 12]]
[[13 14 15 16]
[21 22 23 24]]]
Example
print(f"The slice of a[:,:2,1:3] ⇒ \n {a[:,:2,1:3]}")
Output
The slice of a[:,:2,1:3] ⇒
[[[ 2 3]
[ 6 7]]
[[14 15]
[18 19]]]
Example
print(f"The slice of a[:,::2,::3] ⇒ \n {a[:,::2,::3]}")
Output
The slice of a[:,::2,::3] ⇒
[[[ 1 4]
[ 9 12]]
[[13 16]
[21 24]]]
Note
- To use slice operator, compulsory elements should be in order.
- We cannot select elements which are out of order. Ie we cannot select arbitrary elements.
- Advanced indexing– group of elements which are not in order (arbitrary elements)
When the elements are not ordered then we will go for advanced indexing. To access arbitrary elements(elements which are out of order) we should go for advanced Indexing.
By using index , we can access only one element at a time.
- 1-D array ⇒ a[i].
- -D array ⇒ a[i][j].
- D array ⇒ a[i][j][k].
By using slice operator we can access multiple elements at a time , but all elements should be in order.
- D array ⇒ a[begin:end:step].
- -D array ⇒ a[begin:end:step,begin:end:step].
- D array ⇒ a[begin:end:step,begin:end:step,begin:end:step].
Accessing multiple arbitrary elements in 1-D array
Syntax :
- array[x] ⇒ x can be either ndarray or list, which represents required indices .
1st Way(ndarray)
- create an ndarray with required indices in the given original array.
- pass that array as argument to the original array.
2nd way(list)
- create a list with the required indices in the given original array.
- pass that list as argument to the original array.
Example
a = np.arange(10,101,10)
a
Output
array([ 10, 20, 30, 40, 50, 60, 70, 80,90, 100])
Example
# 1st way (ndarray)
# step1 : create an ndarray with the required indices
# assume that we have to extract 30,50,60,80 elements. Their indices are 2,4,5,8
# create an ndarray with those indices
indices = np.array([2,4,5,8])
indices
Output
array([2, 4, 5, 8])
Example
# step 2: pass the indices as argument to the original array to get the required
arbitrary elements
a[indices]
Output
array([30, 50, 60, 90])
2nd way(using list)
Example
# 2nd way (list)
# Step 1: create a list with the required indices of the original array
l = [2,4,5,8]
#Step 2: pass the list as an argument to the original array to get the required
arbitrary elements
a[l]
Output
array([30, 50, 60, 90])
Accessing multiple arbitrary elements in 2-D array
Syntax:
- a[[row_indices],[column_indices]].

Example
l = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
a = np.array(l)
a[[0,1,2,3],[0,1,2,3]] # It select elements from (0,0),(1,1),(2,2) and (3,3)
Output
array([ 1, 6, 11, 16])
Example
a[[0,1,2,3],[1,3,0,2]]
Output
array([ 2, 8, 9, 15])
Example
# L-shape
a[[0,1,2,3,3,3,3],[0,0,0,0,1,2,3]]
Output
array([ 1, 5, 9, 13, 14, 15, 16])
Note
- In advanced indexing, the required elements will be selected based on indices and with those elements a 1-D array will be created.
- The result of advanced indexing is always 1-D array only even though we select 1-D or 2-D or 3-D array as input.
- But in Slicing the dimension of output array is always same as the dimension of input array.
Example
# Observations :
# 1. a[[0,1,2],[0,1]]
a[[0,1,2],[0,1]]
Output
---------------------------------------------------------------------------
IndexError
Traceback (most recent call last)
<ipython-input-146-c4e1e7026d51> in <module>
2
3 # 1. a[[0,1,2],[0,1]]
----> 4 a[[0,1,2],[0,1]]
IndexError: shape mismatch: indexing arrays could not be broadcast together w
ith shapes (3,) (2,)
Example
# 2. a[[0,1],[0,1,2]]
a[[0,1],[0,1,2]]
Output
---------------------------------------------------------------------------
IndexError
Traceback (most recent call last)
<ipython-input-147-ab01250a8073> in <module>
1 # 2. a[[0,1],[0,1,2]]
----> 2 a[[0,1],[0,1,2]]
IndexError: shape mismatch: indexing arrays could not be broadcast together w
ith shapes (2,) (3,)
Example
# 3. a[[0,1,2],[0]]
a[[0,1,2],[0]] # it will be taken as (0,0),(1,0),(2,0)
Output
array([1, 5, 9])
Example
# 4. a[[0],[0,1,2]]
a[[0],[0,1,2]] # it will be taken as (0,0),(0,1),(0,2)
Output
array([1, 2, 3])
Accessing multiple arbitrary elements in 3-D array
a[i][j][k]
- i represents the index of 2-D array.
- j represents row index.
- k represents column index.
Syntax:
- a[[indices of 2d array],[row indices],[column indices]].

Example
# accessing the arbitrary elements of 3-D arrays
a = np.arange(1,25).reshape(2,3,4)
a
Output
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
Example
# accesing 7 and 18 from the array
a[[0,1],[1,1],[2,1]]
Output
array([ 7, 18])
Summary
To access the arbitrary elements of 1-D array.
- a[x] :: x can be either ndarray or list of indices.
To access the arbitrary elements of 2-D array.
- a[[row_indices],[column_indices]].
To access the arbitrary elements of 3-D array.
- a[[indices of 2e-D array],[row_indices],[column_indices]].
Condition based selection : array_name[condition
- We can select elements of an array based on condition also.
Syntax :: array_name[boolean_array].
- In boolean_array, whereever True is present the corresponding value will be selected.
Example
import numpy as np
a = np.array([10,20,30,40])
boolean_array=np.array([True,False,False,True])
a[boolean_array]
Output
array([10, 40])
Syntax for condition based selection :: array_name[condition].
- condition always return boolean value.
Example
# select elements which are greater than 25 from the given array
a = np.array([10,20,30,40]) # boolean_array should be [False,False,True,True]
# condition will give the boolean value
a>25
Output
array([False, False, True, True])
Example
# create boolean array
bool_array = a>25
# pass the bool_array as argument to the original array
a[bool_array]
Output
array([30, 40])
Example
# in single step also we can achieve the functionality
# array_name[condition]
a[a>25]
Output
array([30, 40])
Example
# select then negative numbers from the given array
a = np.array([10,-5,20,40,-3,-1,75])
a[a<0]
Output
array([-5, -3, -1])
Example
## condition based selection is applicatble for 2-D array also
a = np.arange(1,26).reshape(5,5)
a
Output
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
Example
# select the even numbers from 2-D array
a[a%2==0]
Output
array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24])
Logical operations
- logical_and(x1, x2, /[, out, where, …]) ⇒ Compute the truth value of x1 AND x2 element-wise.
- logical_or(x1, x2, /[, out, where, casting, …]) ⇒ Compute the truth value of x OR x2 element-wise.
- logical_not(x, /[, out, where, casting, …]) ⇒ Compute the truth value of NOT x element-wise.
- logical_xor(x1, x2, /[, out, where, …]) ⇒ Compute the truth value of x1 XOR x2 element-wise.
Example
help(np.logical_and)
In [160]:
# we can select elements by using multiple conditions by using logical operations
# select the elements which are even and divisible by 5
a = np.arange(1,26).reshape(5,5)
b = np.logical_and(a%2==0,a%5==0)
print(f"Original array a ==> \n {a}")
print(f"Logical array b ==> \n {b}")
print(f"Elements which are even and divisible by 5 ==> \n {a[b]}")
Output
Original array a ==>
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]
Logical array b ==>
[[False False False False False]
[False False False False True]
[False False False False False]
[False False False False True]
[False False False False False]]
Elements which are even and divisible by 5 ==>
[10 20]
selecting elements based on multiple conditions
We can use & for AND condition and | for OR condition.
- array_name[(condition_1) & (condition_2)].
- array_name[(condition_1) | (condition_2)].
Example
# select the elements which are divisible by 2 and divisible by 3
a = np.arange(1,26).reshape(5,5)
a[(a%2 == 0) & (a%3 ==0)]
Output
array([ 6, 12, 18, 24])
Example
bool_array = np.logical_and(a%2==0,a%5==0)
a[bool_array]
Output
array([10, 20])
Example
# select the elements either even and divisible by 3
a = np.arange(1,26).reshape(5,5)
a[np.logical_or(a%2==0,a%3==0)]
Output
array([ 2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24])
Example
# select the elments which are divisible by 2 and 3
a = np.arange(1,26).reshape(5,5)
a[(a%2 == 0) & (a%3 ==0)]
Output
array([ 6, 12, 18, 24])
Example
# select the elments which are divisible by either 2 or 3
a = np.arange(1,26).reshape(5,5)
a[(a%2 == 0) | (a%3 ==0)]
Output
array([ 2, 3, 4, 6,,8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24]
Python Slicing Vs Numpy Array Slicing Vs Adv. Indexing Vs. Conditional Selection
case-1 : Python slicing
- In the case of list, slice operator will create a separate copy.
- If we perform any changes in one copy those changes won’t be reflected in othercopy.
Example
# Python Slicing ==> new copy is created
l1 = [10,20,30,40]
l2=l1[::]
l1 is l2
Output
False
Example
# if we made changes in l1 it does not reflect on l2 and vice-versa
l1[0] = 888
print(f"l1::{l1}")
print(f"l2::{l2}")
Output
l1::[888, 20, 30, 40]
l2::[10, 20, 30, 40]
Example
l2[1] = 7777
print(f"l1::{l1}")
print(f"l2::{l2}")
Output
l1::[888, 20, 30, 40]
l2::[10, 7777, 30, 40]
case-2 : Numpy Array Slicing:
- A separate copy won’t be created and just we are getting view of the original copy.
- View is logical entity where as table is physical entity.(RDBMS).
Example
# Numpy array slicing
a = np.arange(10,101,10)
a
Output
array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
Example
# slicing on numpy array
b = a[0:4] # view is created
print(f"b ⇒ {b}")
print(f"a ⇒ {a}")
Output
b ==> [10 20 30 40]
a ==> [ 10 20 30 40 50 60 70 80 90 100]
Example
# if we made changes in b it will reflect on a also vice-versa
b[0] = 999
print(f"After modifying the b array value ⇒ {b}")
print(f"a array value ⇒ {a}")
Output
After modifying the b array value ⇒ [999 20 30 40
a array value ⇒ [999 20 30 40 50 60 70 80 90 100]
Example
a[2] = 888
print(f"After modifying the a array value ⇒ {a}")
print(f"b array value ⇒ {b}")
Output
After modifying the a array value ⇒ [999 20 888 40 50 60 70 80 90 100]
b array value ==> [999 20 888 40]
case-3 : Advanced Indexing and Condition Based Selection
- It will select required elements based on provided index or condition and with those elements a new 1-D array object will be created.
- The output is always a new 1-D array only.
Example
# Advanced Indexing
a = np.arange(10,101,10)
b = a[[0,2,5]]
print(f" a ⇒ {a}")
print(f" b ⇒ {b}")
Output
a ⇒ [ 10 20 30 40 50 60 70 80 90 100]
b ⇒ [10 30 60]
Slicing Vs Advanced Indexing
Slicing
- The elements should be ordered.
- We can’t select arbitrary elements.
- Conditional based selection is not possible.
- Just we will get view but not copy.
- Memeory, performance-wise it is the best.
Advanced indexing
- The elements need not be ordered.
- We can select arbitrary elements.
- Conditional based selection is possible.
- Just we will get separate copy but not view.
- Memeory, performance-wise it is not upto the mark
Summary of syntaxes
Basic Indexing
- 1-D array :: a[i].
- 2-D array :: a[i][j] or a[i,j].
- 3-D array :: a[i][j][k] or a[i,j,k].
Slicing
- 1-D array :: a[begin:end:step].
- 2-D array :: a[begin:end:step,begin.
- 3-D array :: a[begin:end:step,begin:end:step,begin:end:step].
Advanced Indexing
- 1-D array :: a[x] –> x contains required indices of type ndarray or list.
- 2-D array :: a[[row indices],[column indices]].
- 3-D array :: a[[indices of 2D array],[row indices],[column indices]].
Condition based selection
- a[condition] eg: a[a>0].
- This is same for all 1-D, 2-D and 3-D arrays.