按序數(shù)獲取數(shù)據(jù)。不同的書寫方式鉴逞,可能維度會降低归斤,可能跟原先的一樣。
import numpy as np
# 創(chuàng)建一個二維數(shù)組shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
在數(shù)組中間某行獲取數(shù)據(jù)有兩種方式:
整數(shù)和切片混合使用舞丛,會產(chǎn)生較低維的數(shù)組,
而只使用切片會產(chǎn)生與原來數(shù)組同維度的數(shù)組:
row_r1 = a[1, :] # 一維數(shù)組(a的第二行)
row_r2 = a[1:2, :] #二維數(shù)組
print(row_r1, row_r1.shape) # 輸出 "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape) # 輸出 "[[5 6 7 8]] (1, 4)"
獲取數(shù)組一列時耘子,同樣有不同:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)"
print(col_r2, col_r2.shape) # Prints "[[ 2]
# [ 6]
# [10]] (3, 1)"