How to extract data evenly from a Numpy matrix?
You can use the arange function in numpy to achieve evenly spaced data extraction. The arange function generates an evenly spaced array by specifying the start value, end value, and step size.
Here is an example code demonstrating how to use the arange function to evenly extract data.
import numpy as np
# 创建一个矩阵
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 按行等间隔抽取数据
row_indices = np.arange(0, matrix.shape[0], 2)
row_samples = matrix[row_indices, :]
print("按行等间隔抽取数据:")
print(row_samples)
# 按列等间隔抽取数据
col_indices = np.arange(0, matrix.shape[1], 2)
col_samples = matrix[:, col_indices]
print("按列等间隔抽取数据:")
print(col_samples)
The output is:
按行等间隔抽取数据:
[[1 2 3]
[7 8 9]]
按列等间隔抽取数据:
[[1 3]
[4 6]
[7 9]]
In the code above, we first use the arange function to generate row or column indices, and then use these indices to extract data. The first parameter of the arange function is the starting value, the second parameter is the ending value (exclusive), and the third parameter is the step size.