我想选择一个数组中的特定元素,但我想使用一个索引数组来表示第二维,而不是切片,也就是说,我想使用类似于data2d[[dir1,dir2,dir3],0:4]
的数组,但是下面的代码抛出了一个错误:IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,3) (4,)
.
import numpy as np
if __name__ == "__main__":
data2d = np.random.uniform(0.0,1.0,(10,4))
dir1 = np.array([2,1,3])
dir2 = np.array([2,3,3])
dir3 = np.array([1,1,3])
dir4 = np.array([0,1,2,3])
print(data2d[[dir1,dir2,dir3],0:4].shape) # works fine
print(data2d[[dir1,dir2,dir3],dir4].shape) # does not work
pass
我理解维度不匹配的问题,但是我怎么能用索引数组而不是切片访问data2d
的相同元素呢?这一定很简单,但是我找不到一个例子。
2条答案
按热度按时间3phpmpom1#
您的阵列形状:
该索引:
期望值(3,3,4)
尝试使用(3,3),但出现(4,)广播错误;(3,3,1)和(4,)应该有效
gj3fmq9x2#
I understand the issue of the dimension mismatch however how could I access the same elements of data2d with an indexing array instead of slices? It must be simple, but I could not find an example.
numpy数组实现
__getitem__
方法,该方法接受indices
或slice
对象。pythonslice
对象自己处理形状不匹配。例如,如果您用途:打印(二维数据[[目录1,目录2,目录3],0:10].形状)
但是如果你想用numpy数组作为索引,你应该处理形状不匹配或者把它转换成一个
slice
对象。也许np.s_
index expression对转换有用。