不知道大家有沒有一種感覺,每次當使用
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)
"""