   ### Python NumPy »

My Coding > Programming language > Python > Python libraries and packages > Python NumPy

# Python NumPy (Page: 5)

Go to Page:

Mask in NymPy is a simple way to refer few elements from the big NumPy array. Results will be given in the mask format.


import numpy as np

x1 = np.arange(10)**3
m1 = [2, 5, 8]

print(x1)                  # [  0   1   8  27  64 125 216 343 512 729]
print(x1[m1])              # [  8 125 512]

x1[m1] = 111
print(x1)                  # [  0   1 111  27  64 111 216 343 111 729]

Multi-dimentional mask should be created as NumPy array


import numpy as np

x2 = np.arange(10)**3
m2 = np.array([[1, 4], [0, 9]])
print(x1[m2])              # [[  1  64] [  0 729]]

x1[m2] = 222
print(x1)                  # [222 222   8  27 222 125 216 343 512 222]

We can make a mask for two-dimensional arrays as well.


x = np.arange(9).reshape(3,3)
print("x = ", x)                  # [[0 1 2] [3 4 5] [6 7 8]]

# select 1 row
r0 = np.array([])
print("x[r0] = ", x[r0])          # [[[0 1 2]]]

# select 2 rows
r1 = [0, 2]
print("x[r1] = ", x[r1])          # [[0 1 2] [6 7 8]]

# select 2 sets of rows
r2 = np.array([[0, 2], [2, 1]])
print("x[r2] = ", x[r2])          # [[[0 1 2] [6 7 8]]   [[6 7 8] [3 4 5]]]

### Two-dimensional mask - intersection of row and columns

Mask can be created as intersection of rows and columns


# select 1 intersection of 1 row 1 column
r0 = np.array([])
c0 = np.array([])
print("x[r0, c0] = ", x[r0, c0])          # []

# 2 row 1 column => 2 intersections
r1 = np.array([[0, 2]])
c1 = np.array([])
print("x[r1, c1] = ", x[r1, c1])          # [[2 8]]

# Select four corners
r2 = np.array([[0, 0], [2, 2]])
c2 = np.array([[0, 2], [0, 2]])
print("x[r2, c2] = ", x[r2, c2])          # [[0 2] [6 8]]
x[r2, c2] = 10                   # change values to these elements
print(x)                       # [[10  1 10]  [ 3  4  5]  [10  7 10]]

It is possible to generate boolean masks for NumPy array. This mask will have True and Fals elements, which can be used as 1 and 0 in mathematical calculations, respectively. To create this boolean mask, it is nesessary to apply conditions to NumPy array.


x = np.arange(12).reshape(4, 3)
#                [[ 0  1  2]
#                 [ 3  4  5]
#                 [ 6  7  8]
#                 [ 9 10 11]]

idx_b = x > 7
print(idx_b)
#                [[False False False]
#                 [False False False]
#                 [False False  True]
#                 [ True  True  True]]

print(x[idx_b]) # [ 8  9 10 11]
# shorter writing
print(x[x>8])   # [ 9 10 11]

# use math equations over boolean
print(np.sum(x<5, axis = 0))     # [2 2 1]
print(np.sum(x<5, axis = 1))     # [3 2 0 0]

Go to Page: 1; 2; 3; 4; 5; 6;

Published: 2021-10-04 11:48:19
Updated: 2021-11-14 08:41:55

### 9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. 