0
点赞
收藏
分享

微信扫一扫

numpy数组的坐标轴问题


不知道大家有没有一种感觉,每次当使用​​numpy​​​数组的时候坐标轴总是傻傻分不清楚,然后就会十分的困惑,每次运算都需要去尝试好久才能得出想要的结果。这里我们来简单解释一下​​numpy​​​中一维,二维,三维数组的坐标轴问题。
首先我们讨论一维的情况,代码如下:

import numpy as np


class Debug:
def __init__(self):
self.array1 = np.array([0, 1, 2])
self.array2 = np.array([[0], [1], [2]])

def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The shape of array1 is: ")
print(self.array1.shape)
print("The value of array2 is: ")
print(self.array2)
print("The shape of array2 is: ")
print(self.array2.shape)


if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of array1 is:
[0 1 2]
The shape of array1 is:
(3,)
The value of array2 is:
[[0]
[1]
[2]]
The shape of array2 is:
(3, 1)
"""

从上面的结果我们可以看到,一维横数组沿着横向排列,我们可以认定为​​x​​​轴向,它的数组大小为​​(3,)​​​,一维列数组沿着纵向排列,我们可以认为是​​y​​​轴方向,它的大小为​​(3, 1)​​​,我们可以从左向右,看出第二个参数代表的是横向上的参数个数,第一个参数代表的是纵向上的参数个数,因此我们可以将横向数组的大小​​(3,)​​​理解为​​(,3)​​更为合适。

接下来我们研究一下二维数组,哪个参数对应的是横坐标,哪个参数对应的是纵坐标。
代码如下:

import numpy as np


class Debug:
def __init__(self):
self.array1 = np.ones((2, 3))
self.array2 = np.ones((3, 2))

def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The shape of array1 is: ")
print(self.array1.shape)
print("The value of array2 is: ")
print(self.array2)
print("The shape of array2 is: ")
print(self.array2.shape)


if __name__ == '__main__':
main = Debug()
main.mainProgram()

"""
The value of array1 is:
[[1. 1. 1.]
[1. 1. 1.]]
The shape of array1 is:
(2, 3)
The value of array2 is:
[[1. 1.]
[1. 1.]
[1. 1.]]
The shape of array2 is:
(3, 2)
"""

从上面的结果我们可以看出,从左向右,第一个参数代表的是(​​row​​​), 第二个参数代表的是列(​​column​​​)。我们知道​​numpy​​​中默认的是笛卡尔坐标系,所以横向为​​x​​​,纵向为​​y​​​,具体的请看​​坐标系​​​(超链接点击跳转查看)。所以对​​self.array1​​​来说,定义时输入的数组大小的​​(2, 3)​​​代表沿着​​x​​​轴拥有​​3​​​个值,沿着​​y​​​轴拥有​​2​​个值。对比上述得到的结果与我们在一维情况中推断得到的结果,证明我们的理解是正确的。

接着我们讨论三维的情况:代码如下:

import numpy as np


class Debug:
def __init__(self):
self.array1 = np.ones((2, 3, 4))

def mainProgram(self):
print("The value of array1 is: ")
print(self.array1)
print("The shape of array1 is: ")
print(self.array1.shape)


if __name__ == '__main__':
main = Debug()
main.mainProgram()


"""
The value of array1 is:
[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
The shape of array1 is:
(2, 3, 4)
"""

不难发现,沿着​​x​​​轴方向拥有​​4​​​个值,沿着​​y​​​轴方向拥有​​3​​​个值,沿着​​z​​​轴方向拥有​​2​​个值。

综上所述,在numpy数组中,定义三维数组时,从左向右, 第一个参数为​z​轴,第二个参数为​y​轴,第三个参数为​x​轴,即(z, y, x)。 对于各个坐标轴在空间中的朝向问题,建议阅读​​numpy数组坐标轴​​​。之后我们会进一步探讨​​numpy​​模块中的其他与坐标轴相关的函数。


举报

相关推荐

0 条评论