使用两个索引在Numpy中进行逻辑索引,如MATLAB中所示 [英] Logical indexing in Numpy with two indices as in MATLAB

查看:113
本文介绍了使用两个索引在Numpy中进行逻辑索引,如MATLAB中所示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Numpy复制在MATLAB中完成的索引?

How do I replicate this indexing done in MATLAB with Numpy?

X=magic(5);
M=[0,0,1,2,1];
X(M==0,M==2)

返回:

ans =
  8
 14

我发现在Numpy中这样做是不正确的,因为它不会给我相同的结果..

I've found that doing this in Numpy is not correct, since it does not give me the same results..

X = np.matrix([[17, 24,  1,  8, 15],
        [23,  5,  7, 14, 16],
        [ 4,  6, 13, 20, 22],
        [10, 12, 19, 21,  3],
        [11, 18, 25,  2,  9]])

M=array([0,0,1,2,1])
X.take([M==0]).take([M==2], axis=1)

因为我得到:

 matrix([[24, 24, 24, 24, 24]])

在numpy中使用两个索引进行逻辑索引的正确方法是什么?

What is the correct way to logically index with two indices in numpy?

推荐答案

一般来说,有两种方法可以解释 X [a,b] 当a和b都是数组(matlab中的向量),内部样式索引或外部样式索引时。

In general there are two ways to interpret X[a, b] when both a and b are arrays (vectors in matlab), "inner-style" indexing or "outer-style" indexing.

matlab chos的设计者e外部式索引和numpy的设计者选择了内部式索引。要在numpy中进行外部风格索引,可以使用:

The designers of matlab chose "outer-style" indexing and the designers of numpy chose inner-style indexing. To do "outer-style" indexing in numpy one can use:

X[np.ix_(a, b)]
# This is roughly equal to matlab's
X(a, b)

completness你可以在matlab中做内部式索引:

for completness you can do "inner-style" indexing in matlab by doing:

X(sub2ind(size(X), a, b))
# This is roughly equal to numpy's
X[a, b]

简而言之,尝试 X [np.ix_(M == 0,M == 1)]

这篇关于使用两个索引在Numpy中进行逻辑索引,如MATLAB中所示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆