在numpy
模块中的repeat
函数,总是会出现设置axis
坐标轴的情况,这时的坐标轴有时候就显的十分混乱,每到此处就不知道该给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 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]
"""
我们可以看到我们输入的是一个二维数组,当我们设定repeats
值为1
时,输出结果变成了一个一维数组,因此这时的np.repeats
函数类似numpy.ndarray.flatten()函数的功能。
接下来我们研究一下关于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
轴。