Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.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 基于另一个0/1索引数组从numpy数组中提取值_Python_Arrays_Numpy - Fatal编程技术网

Python 基于另一个0/1索引数组从numpy数组中提取值

Python 基于另一个0/1索引数组从numpy数组中提取值,python,arrays,numpy,Python,Arrays,Numpy,给定一个只包含0和1个元素的索引数组idx,1表示感兴趣的样本索引,以及一个样本数组a(a.shape[0]=idx.shape[0])。这里的目标是基于索引向量提取样本子集 在matlab中,执行以下操作非常简单: B = A(idx,:) %assuming A is 2D matrix and idx is a logical vector 如何在Python中以简单的方式实现这一点?如果掩码数组idx与数组a具有相同的形状,那么如果使用astype将idx转换为布尔数组,则应该能够提取

给定一个只包含0和1个元素的索引数组
idx
,1表示感兴趣的样本索引,以及一个样本数组
a
a.shape[0]=idx.shape[0]
)。这里的目标是基于索引向量提取样本子集

在matlab中,执行以下操作非常简单:

B = A(idx,:) %assuming A is 2D matrix and idx is a logical vector

如何在Python中以简单的方式实现这一点?

如果掩码数组
idx
与数组
a
具有相同的形状,那么如果使用
astype
idx
转换为布尔数组,则应该能够提取掩码指定的元素

演示-

>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> idx
array([[1, 0, 0, 1, 1],
       [0, 0, 0, 1, 0],
       [1, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [0, 1, 1, 1, 1]])


如果掩码数组
idx
与数组
A
具有相同的形状,则如果使用
astype
idx
转换为布尔数组,则应该能够提取掩码指定的元素

演示-

>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> idx
array([[1, 0, 0, 1, 1],
       [0, 0, 0, 1, 0],
       [1, 0, 0, 1, 1],
       [1, 0, 0, 1, 1],
       [0, 1, 1, 1, 1]])


使用布尔运算与Matlab中的逻辑运算等效:

B = A[idx.astype(bool)]

使用布尔运算与Matlab中的逻辑运算等效:

B = A[idx.astype(bool)]

A[idx.astype(bool)]
我想是吧?@cᴏʟᴅsᴘᴇᴇᴅ: 你给了答案!!谢谢
A[idx.astype(bool)]
我想是吧?@cᴏʟᴅsᴘᴇᴇᴅ: 你给了答案!!谢谢
在这里是多余的,所以您并不真正需要它。另外,我没有否决。这里的
是多余的,所以你不需要它。而且,我没有投反对票。