Numpy数组索引问题:索引数组的形状不匹配

bmvo0sr5  于 2023-03-18  发布在  其他
关注(0)|答案(2)|浏览(156)

我想选择一个数组中的特定元素,但我想使用一个索引数组来表示第二维,而不是切片,也就是说,我想使用类似于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的相同元素呢?这一定很简单,但是我找不到一个例子。

3phpmpom

3phpmpom1#

您的阵列形状:

data2d # (10,4)
dir1  # (3,)
dir2  # (3,)
dir3  # (3,)
dir4  # (4,)

该索引:

data2d[[dir1,dir2,dir3],0:4]
np.array([dir1,dir2,dir2])  # (3,3)
# index first dim with a (3,3)

期望值(3,3,4)

data2d[[dir1,dir2,dir3],dir4]

尝试使用(3,3),但出现(4,)广播错误;(3,3,1)和(4,)应该有效

arr = np.array([dir1,dir2,dir3])[:,:,None]
data2d[arr, dir4]
gj3fmq9x

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__方法,该方法接受indicesslice对象。python slice对象自己处理形状不匹配。例如,如果您用途:
打印(二维数据[[目录1,目录2,目录3],0:10].形状)
但是如果你想用numpy数组作为索引,你应该处理形状不匹配或者把它转换成一个slice对象。也许np.s_index expression对转换有用。

相关问题