# How To Use Numpy Indexing And Slicing With Examples

In NumPy, if you want to access or modify the elements of an array, you can use indexes or slices, such as accessing the elements of an array using an index starting at 0, which is the same as Python’s list.

### 1. Numpy Slice() Function.

1. The Numpy built-in function slice() can be used to construct slice objects.
2. Using this function, you need to pass three parameters: start (start index), stop (end index), and step.
3. It can create a new array from the original array. Below is an example.
```import numpy as np

def numpy_slice_function():

# create the original array.
src_array = np.arange(16)

# generate the slice object, start index is 2, end index is 16, step is 5.
slice_object = slice(2, 16, 5)

# create tbe target array using the slice object.
target_array = src_array[slice_object]

# print out the target array.
print(target_array)

if __name__ == '__main__':

numpy_slice_function()
```
4. Below is the above example execution output, you can see the number value of the following element is 5 greater than the number of the preceding element.
`[ 2  7 12]`

### 2. Numpy Slicing By Colon.

1. You can also split the slice parameters by colon, and you can get the same result in the end, as shown in the following example.
```import numpy as np

def numpy_slice_with_colon():

# create the original array.
src_array = np.arange(16)

# create the target array using colon split slice.
target_array = src_array[2:16:5]

# print out the target array.
print(target_array)

if __name__ == '__main__':

numpy_slice_with_colon()```
2. Below is the above source code execution result.
`[ 2  7 12]`

### 3. How To Use Colon Slicing.

1. Now let’s make a brief explanation of colon slicing.
2. If you enter only one parameter, the element corresponding to the index is returned. For the above example, src_array returns 6.
`src_array =  6`
3. If the colon is between two number parameters, such as [2:16], all elements between the two index values are sliced (exclude the stopping index)
4. If you insert “:” before a number, such as [: 16], all numbers from 0 to 15 (excluding 16) will be returned.
5. If a colon is placed after a number, such as [5:], a number between 5 (include 5) and 16 ( exclude 16 ) will be returned in the above example.

### 4. Multidimensional Array Slicing.

1. An example of multidimensional array slicing is as follows.
```import numpy as np

def multidimensional_array_slicing():

# define a 2 dimension array.
array = np.array([['python','numpy','pandaas'],['javascript', 'jQuery', 'Angular'],['java', 'spring','ejb']])

print('original array:\r\n')
print(array)

print('\r\n\r\n')

print('sliced array:\r\n')
# slicing from the index 1.
print(array[1:])

if __name__ == '__main__':

multidimensional_array_slicing()```
2. Below is the above example execution output.
```original array:

[['python' 'numpy' 'pandaas']
['javascript' 'jQuery' 'Angular']
['java' 'spring' 'ejb']]

sliced array:

[['javascript' 'jQuery' 'Angular']
['java' 'spring' 'ejb']]```
3. You can also use the ellipsis “” when using slicing. If the ellipsis is used at the row position, the return value will contain all row elements, otherwise, it will contain all column elements.
```import numpy as np

def array_slicing_with_ellipsis():

# define a 2 dimension array.
array = np.array([['python','numpy','pandas'],['javascript', 'jQuery', 'Angular'],['java', 'spring','ejb']])

print('original array:\r\n')
print(array)

print('\r\n\r\n')

print('slice the second column to an array:\r\n')
print(array[..., 1])

print('\r\n\r\n')

print('slice the second row to an array:\r\n')
# slicing from the index 1.
print(array[1, ...])

print('\r\n\r\n')

print('return all elements in the second column and beyond to an array:\r\n')
print(array[..., 1:])

if __name__ == '__main__':

array_slicing_with_ellipsis()```
4. Below is the above example source code execution result.
```original array:
[['python' 'numpy' 'pandas']
['javascript' 'jQuery' 'Angular']
['java' 'spring' 'ejb']]

slice the second column to an array:
['numpy' 'jQuery' 'spring']

slice the second row to an array:
['javascript' 'jQuery' 'Angular']

return all elements in the second column and beyond to an array:
[['numpy' 'pandas']
['jQuery' 'Angular']
['spring' 'ejb']]
```

### 5. Integer Array Index.

1. Integer array index, which can select any element in the array. For example, select an element in the row and column. An example is as follows.
```import numpy as np

def integer_array_index():

# Create a 2D array
array = np.array([['python',  'numpy'],  ['pandas',  'matplotlib'],  ['pillow',  'pygame']])

# [1,0,2] represents the row index; [1,0,1] represents the column index.
# the result array elements are array[1,1] ( 'matplotlib' ), array[0,0] ( 'python' ), array[2,1] ( 'pygame' )
array_elements_by_index = array[[1,0,2],[1,0,1]]

print (array_elements_by_index)

if __name__ == '__main__':

integer_array_index()```
2. Below is the above example execution output.
`['matplotlib' 'python' 'pygame']`
3. You can also use the colon(:) or ellipsis() which is used by the slice in combination with the integer array index, below is an example.
```import numpy as np

def integer_array_index_with_colon_ellipsis():

# define a 2 dimension array object which contains
array = np.array([[ 'r0c0',  'r0c1',  'r0c2'],
[ 'r1c0',  'r1c1',  'r1c2'],
[ 'r2c0',  'r2c1',  'r2c2'],
[ 'r3c0', 'r3c1', 'r3c2']])

# slice the rows and columns separately, return the elements in row1, row2 and in col1, col2.
x = array[1:3,1:3]
print('array[1:3,1:3]\r')
print(x)

print('\r\n')

# slice indexes are used for rows, and basic indexes are used for columns, below code will return elements in row1, row2, row3 and in col1, col2.
y = array[1:4,[1,2]]
print('array[1:4,[1,2]]\r')
print (y)

print('\r\n')

# use ellipsis indexes for rows, and slice indexes for columns, the below code will return all elements in row0, row1, row2,row3 and col2.
z = array[...,1:]
print('array[...,1:]\r')
print(z)

if __name__ == '__main__':

integer_array_index_with_colon_ellipsis()
```
4. Below is the above example source code execution result.
```array[1:3,1:3]

[['r1c1' 'r1c2']
['r2c1' 'r2c2']]

array[1:4,[1,2]]

[['r1c1' 'r1c2']
['r2c1' 'r2c2']
['r3c1' 'r3c2']]

array[...,1:]

[['r0c1' 'r0c2']
['r1c1' 'r1c2']
['r2c1' 'r2c2']
['r3c1' 'r3c2']]```
5. Below are some integer index array examples.
```import numpy as np

def integer_array_index_examples():

'''
When the original array is a one-dimensional array and the one-dimensional array use integer as the index,
the index result is the element at the corresponding index position
'''
src_array = np.array(['python', 'java', 'javascript'])
print('\nsrc_array : ', src_array)
print('\nsrc_array : ', src_array)

'''
If the original array is a two-dimensional array, the index array also needs to be two-dimensional.
The element value of the index array corresponds to each row of the indexed array.
'''
src_array = np.arange(15)
# the original array is one dimensional array.
print('\nsrc_array : ', src_array)
# reshape the original array to 2 dimensional array.
reshape_array = src_array.reshape((3, 5))
print('\nreshape_array : \n', reshape_array)
# print out the row3, row1, and row2.ß
print('\nreshape_array by row index : \n', reshape_array[[2,0,1]])

print('\nreshape_array by reverse order : \n', reshape_array[[-1, -2, -3]])

if __name__ == '__main__':

integer_array_index_examples()
```
6. When you run the above example, you will get the below output.
```src_array :  ['python' 'java' 'javascript']

src_array :  java

src_array :  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]

reshape_array :
[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]]

reshape_array by row index :
[[10 11 12 13 14]
[ 0  1  2  3  4]
[ 5  6  7  8  9]]

reshape_array by reverse order :
[[10 11 12 13 14]
[ 5  6  7  8  9]
[ 0  1  2  3  4]]```

### 6. Boolean Array Index.

1. Another advanced form of indexing, boolean array indexing, is used when the output results require a boolean operation, such as a comparison operation.
2. The below example returns all elements in an array smaller than 9.
```import numpy as np

def boolean_array_index():

# define an array variable that contains the integer number 0 - 10
array = np.array([[ 0,  1,  2],[ 3,  4,  5],[ 6,  7,  8],[ 9, 10, 11]])

# return all the number which is smaller than 9.
array1 = array[array < 9]

print (array1)

if __name__ == '__main__':

boolean_array_index()```
3. Below is the above source code execution result.
`[0 1 2 3 4 5 6 7 8]`
4. When the Numpy array contains NaN value( none numeric value ), we can use the Numpy module’s isnan() method to check whether the value is NaN value or not, if the value is NaN value, then we can use the ~ operator to remove the NaN values in the array.
```import numpy as np

def remove_nan_value():

# the np.nan will create a NaN value.
x = np.array([np.nan, 5, np.nan, 6, 7, 8, 9])

print('original array : ', x)

print('remove NaN value array : ', x[~np.isnan(x)])

if __name__ == '__main__':

remove_nan_value()```
5. Below is the above example output when you run it.
```original array :  [nan  5. nan  6.  7.  8.  9.]
remove NaN value array :  [5. 6. 7. 8. 9.]```
6. Below example demo of how to use the Numpy iscomplex() method, and how to remove the complex number in the Numpy array.
```import numpy as np

def remove_complex_number_in_array():

# define an array with integer and complex number elements.
x = np.array([6, 1+8j, 9, 6+6j])

print('x : ', x)

# use Numpy module's iscomplex() method to check whether the element is complex number or integer number, and then remove the complex number.
print('x[~np.iscomplex(x)] : ', x[~np.iscomplex(x)])

if __name__ == '__main__':

remove_complex_number_in_array()```
7. When you run the above example, you will get the below result.
```x :  [6.+0.j 1.+8.j 9.+0.j 6.+6.j]
x[~np.iscomplex(x)] :  [6.+0.j 9.+0.j]```

This site uses Akismet to reduce spam. Learn how your comment data is processed. 