【问题标题】:Is there a numpy function that mimics A[[i,j],...][...,[a,b,c]] but is not read only?是否有一个模仿 A[[i,j],...][...,[a,b,c]] 但不是只读的 numpy 函数?
【发布时间】:2019-06-04 03:41:31
【问题描述】:

我正在尝试使用 numpy 和一些稀疏矩阵进行一些矩阵计算。为此,我想忽略矩阵中的零并只访问一些值,但我还需要覆盖它们。

import numpy as np

a=np.random.rand(5,5)
#does not change a:
a[[1,2],...][...,[1,2]]=np.array([[0,0],[0,0]])
#just changes (1,1) and (2,2)
a[[1,2],[1,2]]=np.array([0,0])

我想用零覆盖 [1,1],[1,2],[2,1],[2,2]。

【问题讨论】:

  • 这里到底有什么问题? a[[1,2],[1,2]]=np.array([0,0]) 有什么问题?
  • 它只是覆盖(1,1)和(2,2),但我想覆盖(1,1),(1,2),(2,1)和(2, 2)!
  • a[[[1], [2]], [1,2]]= 0a[np.ix_([1,2], [1,2])]=0

标签: python numpy


【解决方案1】:

我认为你需要这样的东西:

import numpy as np

a = np.arange(25).reshape((5, 5))
i, j = np.ix_([1, 2], [1, 2])
a[i, j] = np.zeros((2, 2))
print(a)
# [[ 0  1  2  3  4]
#  [ 5  0  0  8  9]
#  [10  0  0 13 14]
#  [15 16 17 18 19]
#  [20 21 22 23 24]]

【讨论】:

    【解决方案2】:

    任何给定索引列表的一种通用方法是简单地遍历要分配 0 的索引对

    import numpy as np
    
    a=np.random.rand(5,5)
    indices = [[1,1],[1,2],[2,1],[2,2] ]
    
    for i in indices:
        a[tuple(i)] = 0
    
    print (a)
    
    array([[0.16014178, 0.68771817, 0.97822325, 0.30983165, 0.60145224],
       [0.10440995, 0.        , 0.        , 0.09527387, 0.38472278],
       [0.93199524, 0.        , 0.        , 0.11230965, 0.81220929],
       [0.91941358, 0.96513491, 0.07891327, 0.43564498, 0.43580541],
       [0.94158242, 0.78145344, 0.73241028, 0.35964791, 0.62645245]])
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2021-12-17
      • 2013-03-01
      相关资源
      最近更新 更多