【问题标题】:Extracting sub elements from a matrix in python从python中的矩阵中提取子元素
【发布时间】:2018-09-23 19:33:55
【问题描述】:

我有这个矩阵:

0   0   0   138
0   8   0   0
0   1   0   0
131 0   0   138
0   0   138 0
0   0   0   0
0   115 0   8

还有这个索引向量:

idx = [2,4,5]

我需要从矩阵中获取所有具有 138 的条目的行索引和列索引,但是,仅针对 idx 中的行。

【问题讨论】:

  • 你的矩阵是如何存储的?

标签: python arrays python-3.x numpy matrix


【解决方案1】:

如果你像这样存储矩阵:

matrix = [ [0, 0, 0, 138], [0, 8, 0, 0], ... ]

那么你的工作就很简单了:

result = []
for i in idx:
    row = matrix[i]
    for j in range(len(row)):
        if row[j] == 138:
            result.append((i, j))
return result

【讨论】:

  • 我也是这样做的,但是我想要下面这样的东西。
【解决方案2】:

由于您使用的是numpy,因此您应该尝试以矢量化方式执行此操作:

import numpy as np

A = np.array([[0, 0, 0, 138],
              [0, 8, 0, 0],
              [0, 1, 0, 0],
              [131, 0, 0, 138],
              [0, 0, 138, 0],
              [0, 0, 0, 0],
              [0, 115, 0, 8]])

idx = np.array([2, 4, 5])

match = np.argwhere(A == 138)
res = match[np.in1d(match[:, 0], idx)]

# array([[4, 2]], dtype=int64)

【讨论】:

    【解决方案3】:

    直接在A上使用行索引,然后搜索138

    >>> import numpy as np
    >>> 
    >>> A = np.array([[0, 0, 0, 138],
    ...               [0, 8, 0, 0],
    ...               [0, 1, 0, 0],
    ...               [131, 0, 0, 138],
    ...               [0, 0, 138, 0],
    ...               [0, 0, 0, 0],
    ...               [0, 115, 0, 8]])
    >>> 
    >>> idx = np.array([2, 4, 5])
    >>> 
    >>> y, x = np.where(A[idx]==138)
    >>> y = idx[y]
    >>> y, x
    (array([4]), array([2]))
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多