Skip to main content
 首页 » 编程设计

python之bool 索引但结果是一些其他操作

2024年10月25日9del

我正在尝试做 bool 索引 但是..

np.random.randn(8).reshape((4,2)) 
Out[11]:  
array([[-1.13058416,  1.08397186], 
       [-1.2730122 ,  0.78306498], 
       [-0.05370502, -1.16723298], 
       [ 1.01750955, -0.95029671]]) 
 
a=np.random.randn(8).reshape((4,2)) 
 
a[[2==3,3==0,0==0,1!=1]] 
Out[13]:  
array([[ 0.18235299, -2.53482367], 
       [ 0.18235299, -2.53482367], 
       [-1.03752809, -2.2790847 ], 
       [ 0.18235299, -2.53482367]]) 

刚刚发生了什么? 我在想更像是 Bool 索引。这是什么操作? 我不是要将此更正为 Bool 索引。相反,我问这个操作发生了什么?这是合法的吗?

请您参考如下方法:

很容易将 ndarray 视为增强的 list。数组上的广播和操作会自动扩展到涉及这些操作的列表,因此您可以添加一个数组和一个广播兼容形状列表,numpy 不会尝试连接这两个(因为它会尝试连接两个列表).

一个巨大的(对我来说,令人困惑的)异常(exception)是 fancy indexing .花式索引本身已经让我感到困惑(作为来自 MATLAB 的人),因为以下两个给出不同的结果很奇怪:

import numpy as np 
A = np.random.rand(3,3) 
A[0:1,0:1] 
A[range(2),range(2)] 

前者是一个切片操作,返回一个 2×2 的子矩阵。后者是花式索引的情况,只返回一个 2 元素数组,包含 A[0,0] 和 A[1,1]。

您的问题与同样奇怪的事情有关: bool 值 的列表和数组在花式索引中使用时表现不同。根据您的问题考虑以下两个示例:

A = np.random.rand(4,2) 
bool_index_list = [False, True, True, False] 
bool_index_array = np.array(bool_index_list) 
A[bool_index_list].shape 
A[bool_index_array].shape 

前者返回(4,2),后者返回(2,2)。

在前一种情况下,由于索引是一个列表, bool 值被转换为相应的整数,而结果值是[0,1,1,0] 用作矩阵中的实际索引,分别返回 [first,second,second,first] 行。

在后一种情况下,dtype=bool 的索引 array 被用作您期望的那样:它被用作掩码以忽略那些行A,其索引为 False。

numpy release notes ,除其他事项外,表明

In the future Boolean array-likes (such as lists of python bools) will always be treated as Boolean indexes and Boolean scalars (including python True) will be a legal boolean index.

相应地,上面的基于列表的索引案例在 numpy 1.10.1 中给我以下警告:

FutureWarning: in the future, boolean array-likes will be handled as a boolean array index

所以对您的问题的简短回答是它是合法的,但时间不长。坚持使用基于 ndarray 的花式索引,您应该不会遇到任何障碍。