Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在numpy中使用布尔数组索引会导致ValueError_Python 3.x_Numpy_Indexing_Boolean - Fatal编程技术网

Python 3.x 在numpy中使用布尔数组索引会导致ValueError

Python 3.x 在numpy中使用布尔数组索引会导致ValueError,python-3.x,numpy,indexing,boolean,Python 3.x,Numpy,Indexing,Boolean,我试着用布尔数组建立索引 def boolean_array_indexing_each_dim1(): a = np.array( [ ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p']

我试着用布尔数组建立索引

def boolean_array_indexing_each_dim1():
    a = np.array(
                 [
                  ['a','b','c','d'],
                  ['e','f','g','h'],
                  ['i','j','k','l'],
                  ['m','n','o','p']
                  ]
                 )
    print('a=\n',a.shape,'\n',a)
    b1 = np.array([True,True,True,False]) #gives error
    #b1 = np.array([True,False,True,False]) #works
    print('b1=\n',b1.shape,'\n',b1)
    b2 = np.array([True,False,True,False])
    print('b2=\n',b2.shape,'\n',b2)  
    selected = a[b1,b2]
    print('selected=\n',selected.shape,'\n',selected)
数组
b1=np。数组([True,True,True,False])
导致“ValueError形状不匹配:对象无法广播到单个形状”

数组
b1=np.array([True,False,True,False])
但是可以工作并产生一个结果“['a'k']”


为什么会发生这种错误?有人能告诉我吗

原因是第一个
b1
数组有3个
True
值,第二个数组有2个
True
值。它们分别相当于通过
[0,1,2],[0,2]
建立索引。Numpy的索引“工作”是根据
b1
b2
数组中的位置序列构造索引对。对于
[0,1,2],[0,2]
的情况,它构造索引对
(0,0)、(1,2)
,但是
b1
中没有最后的
2
的伙伴,因此它会引发
ValueError
。您的备用
b1
有效,因为它恰好与您的
b2
具有相同数量的
True

我怀疑你打算完成的是

selected = a[b1,:][:,b2]
这将始终沿轴0使用
b1
对阵列进行切片,然后沿轴1使用
b2
对其进行切片