【问题标题】:Python: How do you make a variable which can be used as an index call to slice another variable?Python:如何创建一个变量,该变量可以用作索引调用来切片另一个变量?
【发布时间】: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],但在现实生活中我有更复杂的情况,我无法手动写出索引。

我曾尝试使用 rangenp.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] 也有效(尽管结果中存在一些字幕差异)。您如何使用rangenot callable 建议您使用 (),而 Python 期望使用 []
  • 在 py3 中,range(n,m) 是一个 range 对象。 list(range(n,m)) 把它变成一个列表。

标签: python arrays matlab numpy indexing


【解决方案1】:

你需要slice:

>>> import numpy as np
>>> A = np.array([[2,3,4,5,6],[9,4,3,2,1],[5,4,3,2,5]])
>>> begin = 1
>>> end = 3
>>> s = slice(begin, end)
>>> A[:,s]
array([[3, 4],
       [4, 3],
       [4, 3]])

【讨论】:

    【解决方案2】:

    你需要这样做

    idx = range(begin, end + 1)
    

    请注意,您需要将 1 添加到最终值,因为范围不包括最终值,即以 end - 1 结尾

    【讨论】:

      【解决方案3】:

      “冻结”索引表达式的一种相当通用且方便的方法是np.s_

      a = np.arange(12).reshape(3, 4)
      idx = np.s_[1:3]
      a[:, idx]
      # array([[ 1,  2],
      #        [ 5,  6],
      #        [ 9, 10]])
      idx = np.s_[::2, [1, 3, 0]]
      a[idx]
      # array([[ 1,  3,  0],
      #        [ 9, 11,  8]]) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多