0
点赞
收藏
分享

微信扫一扫

np.repeat()的坐标轴问题


在​​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​​轴。


举报

相关推荐

0 条评论