在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轴。
如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~




