Skip to main content
 首页 » 编程设计

Python NumPy : referencing columns

2025年05月04日11xxx_UU

为什么是 array1[:][1] != array1[:,1] ?

例如:

array1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 
array1[1] ## Output: array([4,5,6]) as expected 
array1[:,1] ## Output: array([2, 5, 8]) as expected 
array1[:][1] ## Output: array([4,5,6]) which isn't what I expected! 

当使用双括号引用时,array1[:] 组件是否首先执行并返回完整的 2D 数组?因此 array1[:][1] == array1[1]?

请您参考如下方法:

NumPy 会将 a[:] 解释为数组的副本而不是“行”集。基本切片仅类似于连续切片,直到出现 : 条目。来自文档(第 1.4 节 - 索引):

Basic slicing with more than one non-: entry in the slicing tuple, acts like repeated application of slicing using a single non-: entry, where the non-: entries are successively taken (with all other non-: entries replaced by :). Thus, x[ind1,...,ind2,:] acts like x[ind1][...,ind2,:] under basic slicing.

当 : 条目被处理时,有一个隐含的复杂性。