【发布时间】:2020-12-21 08:02:13
【问题描述】:
问题
请帮助理解 Numpy 将元组 (i, j) 索引到 ndarray 的设计决策或合理性。
背景
当索引为单个元组 (4, 2) 时,则为 (i=row, j=column)。
shape = (6, 7)
X = np.zeros(shape, dtype=int)
X[(4, 2)] = 1
X[(5, 3)] = 1
print("X is :\n{}\n".format(X))
---
X is :
[[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 1 0 0 0 0] <--- (4, 2)
[0 0 0 1 0 0 0]] <--- (5, 3)
但是,当索引是多个元组 (4, 2), (5, 3) 时,则 (i=row, j=row) 为 (4, 2) 和 (i=column, j=column) (5, 3)。
shape = (6, 7)
Y = np.zeros(shape, dtype=int)
Y[(4, 2), (5, 3)] = 1
print("Y is :\n{}\n".format(Y))
---
Y is :
[[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 1 0 0 0] <--- (2, 3)
[0 0 0 0 0 0 0]
[0 0 0 0 0 1 0] <--- (4, 5)
[0 0 0 0 0 0 0]]
这意味着你正在构造一个二维数组R,例如
R=A[B, C]。 这意味着值 rij=abijcij.所以这意味着位于
R[0,0]的项目是A中的项目 作为行索引B[0,0]和列索引C[0,0]。项目R[0,1]是A中的项目,具有行索引B[0,1]并作为列索引C[0,1]等
multi_index:整数数组的元组,每个维度一个数组。
为什么不总是(i=行,j=列)?如果总是 (i=row, j=column) 会发生什么?
更新
根据 Akshay 和 @DaniMesejo 的回答,明白了:
X[
(4), # dimension 2 indices with only 1 element
(2) # dimension 1 indices with only 1 element
] = 1
Y[
(4, 2, ...), # dimension 2 indices
(5, 3, ...) # dimension 1 indices (dimension 0 is e.g. np.array(3) whose shape is (), in my understanding)
] = 1
【问题讨论】:
-
总是
i = row和j = column。你的解释是错误的。在您的第一个示例中,括号是多余的(与 X[4, 2] 相同)。其中 4 是第一个轴的索引,2 是第二个轴的索引。因此,逗号之前的每个值都用于行,而逗号之后的每个值都用于列。但问题是您可以为行和列传递多个值,例如 Y[(4, 2), (5, 3)],因为逗号之前的所有值都用于第一个轴,后面的一个逗号用于第二个轴。 -
@DaniMesejo,感谢您指出“逗号之前的值用于第一个轴,逗号后面的值用于第二个轴”。
标签: python numpy matrix-indexing