【发布时间】:2018-05-06 21:00:56
【问题描述】:
我来自 MATLAB 背景并转向 Python。我试图找出一种方法来设置一个变量,该变量是一个包含一系列索引的向量,然后可以用来切片其他数组。
在 MATLAB 中我会这样做:
A = [2,3,4,5,6; 9,4,3,2,1; 5,4,3,2,5]; %some arbitrary matrix
begin = 2; %the first index I want to pull
end = 4; %the last index I want to pull
idx = 2:4; %the vector of indices I want
A(:,idx) %results in me pulling out the 2nd, 3rd and 4th column of A
现在在 Python 中,什么是等价的?
import numpy as np
A = np.array([[2,3,4,5,6],[9,4,3,2,1],[5,4,3,2,5]]) #some arbitrary matrix
begin = 1 #first index
end = 3 #last index
idx = ??? #This is the part I don't know! <<<-------------------
A[:,idx] #I want the same result as the Matlab example above
显然,对于这个简单的例子,我可以只使用idx = [1,2,3],但在现实生活中我有更复杂的情况,我无法手动写出索引。
我曾尝试使用 range 和 np.arange 函数,但它们给出的错误是对象不可调用。
当我查看一些 MATLAB 到 Numpy 的转换,例如 here 时,它表明 MATLAB 命令中的 idx = 2:4 命令等同于 Python 中的 idx = range(1,3),但这显然不是真的?
感谢任何帮助。
【问题讨论】:
-
A[:,np.arange(1,4)],A[:, range(1,4)]都为我工作。A[:,1:4]也有效(尽管结果中存在一些字幕差异)。您如何使用range?not callable建议您使用(),而 Python 期望使用[]。 -
在 py3 中,
range(n,m)是一个range对象。list(range(n,m))把它变成一个列表。
标签: python arrays matlab numpy indexing