当前位置:网站首页>Common operations of numpy on two-dimensional array

Common operations of numpy on two-dimensional array

2022-07-08 01:23:00 You roll, I don't roll

Catalog

1、 Extract some columns or rows of a two-dimensional array

2、 Get a range of data

3、 Sum all the elements

4、 Calculate the number of non-zero elements in the array

5、 Extract certain rows or columns using Boolean masks

6、 Get the number of rows or columns of the array

7、 Get the last column ( Or yes ) The elements of


1、 Extract some columns or rows of a two-dimensional array

import numpy as np
#  Definition  3*3  Of  numpy  Array 
matrix = np.array([[1, 3, 2], 
                   [8, 0, 6], 
                   [9, 7, 0]])
#  To extract the first 1、3 Column ( The extraction of rows is the same )
matrix1 = matrix[:, [0, 2]]
print(matrix1)

# ==========  result  ========== #
[[1 2] 
 [8 6] 
 [9 0]]

2、 Get a range of data

#  For the first 1、2 In line 1、3 Columns of data .  Be careful  0:2  Represents the interval of left closed and right open 
matrix1 = matrix[0:2, [0, 2]]
print(matrix1)

# ========  result  ======== #
[[1 2]
 [8 6]]

3、 Sum all the elements

#  Yes  matrix  Array sum 
num = matrix.sum()
print(num)

# ========  result  ======== #
36

4、 Calculate the number of non-zero elements in the array

#  Determine whether the element in each position is non-zero 
matrix2 = (matrix != 0)
#  Sum Boolean matrices 
N0_num = matrix2.sum()
print(matrix2)
print(N0_num)

# ========  result  ======== #
[[ True  True  True] 
 [ True False  True] 
 [ True  True False]]
7

5、 Extract certain rows or columns using Boolean masks

#  The goal is to extract the  1、3  Column ( Or yes ),  Its  size  Must correspond to the number of columns ( Or number of rows ) identical 
bool_mask = [True, False, True]
#  Use  bool_mask  Extract the corresponding column ( The same is true for withdrawal lines )
matrix3 = matrix[:, bool_mask]
print(matrix3)

# ========  result  ======== #
[[1 2]
 [8 6]
 [9 0]]

6、 Get the number of rows or columns of the array

#  obtain  matrix1  Dimensions , The result is in the form of tuples 
size = matrix1.shape
#  Get the number of lines 
row = size[0]
#  Get the number of columns 
col = size[1]
print(size)
print(row)
print(col)

# ========  result  ======== #
(3, 2)
3
2

7、 Get the last column ( Or yes ) The elements of

#  obtain  matrix  The last column of elements , The result is a one-dimensional array . Get the same reason of the last line 
end_col = matrix[:, -1]
print(end_col)

# ========  result  ======== #
[2 6 0]

 

原网站

版权声明
本文为[You roll, I don't roll]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130542480290.html