以下行為的解釋是什么:
import numpy as np
arr = np.zeros((3, 3))
li = [1,2]
print('output1:', arr[:, li].shape)
print('output2:', arr[:][li].shape)
>>output1: (3, 2)
>>output2: (2, 3)
我希望output2等于output1。
以下行為的解釋是什么:
import numpy as np
arr = np.zeros((3, 3))
li = [1,2]
print('output1:', arr[:, li].shape)
print('output2:', arr[:][li].shape)
>>output1: (3, 2)
>>output2: (2, 3)
我希望output2等于output1。
公眾號:1024技術圈
?? 提供互聯網知識和資訊,分享IT前沿技術,熱門資源,大廠面試題 ??
讓我們使用一個更容易看出差異的不同數組:
第一種情況
arr[:, li]
將從第一個維度中選擇所有元素(在本例中為所有行),然后使用[1, 2]
對數組進行索引,這意味著省略第一列:因此,它的形狀是(3,2)。
另一種情況
arr[:]
將復制原始數組,因此它不會改變形狀,因此它與arr[li]
等價,因此輸出形狀是(2, 3)
。一般來說,應該避免對數組進行雙重索引,因為這樣可能會創建兩次視圖,這是低效的。