Indexing and Slicing
Indexing and Slicing
BY
MR.Naveen kumar M.tech
Introduction
To get some specific data or elements from numpy
arrays, NumPy indexing and slicing are used. Indexing
starts from 0 and slicing is performed using indexing.
Indexing an Array
Index 0 1 2 3 4 5 6 7
Types of Indexing
There are two types of indexing:
1. Index Arrays
2. Integer indexing
3. Advanced indexing
1. Index Arrays
We can index an element of the array using two indices - i selects the row, and j selects the column:
print(a2[2, 1]) # 8
2. Integer Indexing
y = x[[0,1,2], [0,0,1]]
print("The Output is:")
print(y)
Output
0 [[11 28]
2 [95 56]]
Syntax
<slice> = array[start:stop:step]
Here:
start - index of the first element to be included in the slice
The minus operator is used to refer to an index from the end of an array;
you slice an array from the end instead of from the start.
Example: Slice from index 4 (from the end) to index 2 (from the end).
Slicing 2-D arrays
Ex:
Import numpy as np
A=np.array([1,2,3,4,5,6,7])
B=np.array([2,4,6,8,10,12,14])
C=A*B;
Print (C)
Output:
[2,8,18,32,50,72,98]