np.repeat函数
在
numpy
模块中的
repeat
函数,总是会出现设置
axis
坐标轴的情况,这时的坐标轴有时候就显的十分混乱,每到此处就不知道该给
axis
什么值。特写一篇博客来详细说明这个问题。
使用np.repeat()展平二维数组
代码如下:
import numpy as np
class Debug:
def __init__(self):
self.array1 = np.array([[1, 2], [3, 4]])
def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The repeated array is: ")
array2 = np.repeat(self.array1, repeats=1)
print(array2)
if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of array1 is:
[[1 2]
[3 4]]
The repeated array is:
[1 2 3 4]
"""
我们可以看到我们输入的是一个二维数组,当保持 axis
参数为默认值 None
(即不设定 axis
参数),同时我们设定 repeats
值为 1
时,输出结果变成了一个一维数组,因此这时的 np.repeats
函数类似numpy.ndarray.flatten()函数的功能。
np.repeat()函数的坐标轴问题
接下来我们研究一下关于 axis
坐标轴的问题。
二维
对于数组是二维的情况,代码如下:
import numpy as np
class Debug:
def __init__(self):
self.array1 = np.array([[1, 2], [3, 4]])
def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The array2 is: ")
array2 = np.repeat(self.array1, repeats=2, axis=0)
print(array2)
print("The array3 is: ")
array3 = np.repeat(self.array1, repeats=2, axis=1)
print(array3)
if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of array1 is:
[[1 2]
[3 4]]
The array2 is:
[[1 2]
[1 2]
[3 4]
[3 4]]
The array3 is:
[[1 1 2 2]
[3 3 4 4]]
"""
我们可以看到,axis=0
时表示沿着y
方向重复,axis=1
时表示沿着x
方向重复。我们可以对比numpy数组的坐标轴表示,二维时,坐标轴为 (y, x)
,从左向右第一个参数 0
便代表 y
轴,1
代表 x
轴。
三维
接下来我们研究一下数组是三维的情况,代码如下:
import numpy as np
class Debug:
def __init__(self):
self.array1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The array2 is: ")
array2 = np.repeat(self.array1, repeats=2, axis=0)
print(array2)
print("The array3 is: ")
array3 = np.repeat(self.array1, repeats=2, axis=1)
print(array3)
print("The array4 is: ")
array4 = np.repeat(self.array1, repeats=2, axis=2)
print(array4)
if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of array1 is:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
The array2 is:
[[[1 2]
[3 4]]
[[1 2]
[3 4]]
[[5 6]
[7 8]]
[[5 6]
[7 8]]]
The array3 is:
[[[1 2]
[1 2]
[3 4]
[3 4]]
[[5 6]
[5 6]
[7 8]
[7 8]]]
The array4 is:
[[[1 1 2 2]
[3 3 4 4]]
[[5 5 6 6]
[7 7 8 8]]]
"""
我们可以看到,axis=0
对应与沿着z
轴重复,axis=1
对应沿着y
轴重复,axis=2
对应沿着x
轴重复。对比numpy坐标轴的表示,我们知道三维坐标轴为 (z, y, x)
,所以从左向右,0
对应z
轴,1
对应 y
轴,2
对应 x
轴。
如果大家觉得有用,就请点个赞吧~