【问题标题】:Replace python numpy matrix value based on a condition, without using a for loop根据条件替换python numpy矩阵值,而不使用for循环
【发布时间】:2019-10-31 01:30:52
【问题描述】:

例如,我有一个对称的 numpy 矩阵。

matrix([[0.   , 0.125, 0.75 , 0.   , 0.   ],
        [0.125, 0.   , 0.   , 0.   , 0.   ],
        [0.75 , 0.   , 0.   , 0.   , 0.375],
        [0.   , 0.   , 0.   , 0.   , 1.2  ],
        [0.   , 0.   , 0.375, 1.2  , 0.   ]])

如果数组中的某个值大于零,是否可以将该值替换为给定行和列之和的乘积。例如,0.125 将被 0.109375 替换,因为 row_sum * col_sum = 0.125 *(0.125+0.75)=0.109375。

我知道它可以使用 for 循环来完成,但是是否可以使用标准 numpy 库来完成,因为我想避免 for 循环。

【问题讨论】:

  • 怎么样? np。 matmul(np.ones(matrix.shape), 矩阵) * np.matmul(matrix, np.ones(matrix.shape))

标签: python-3.x numpy matrix


【解决方案1】:

声明给定的矩阵

import numpy as np
arr=np.array([[0.   , 0.125, 0.75 , 0.   , 0.   ],
            [0.125, 0.   , 0.   , 0.   , 0.   ],
            [0.75 , 0.   , 0.   , 0.   , 0.375],
            [0.   , 0.   , 0.   , 0.   , 1.2  ],
            [0.   , 0.   , 0.375, 1.2  , 0.   ]])

将列表理解和 np.argwhere 用于条件索引:

def replace(x,y,arr=arr,column_sums=arr.sum(axis=0),row_sum=arr.sum(axis=1)):
    arr[x][y]=row_sum[x]*column_sums[y]

_=[replace(x,y) for x,y in np.argwhere(arr>0)]

输出:

array([[0.      , 0.109375, 0.984375, 0.      , 0.      ],
       [0.109375, 0.      , 0.      , 0.      , 0.      ],
       [0.984375, 0.      , 0.      , 0.      , 1.771875],
       [0.      , 0.      , 0.      , 0.      , 1.89    ],
       [0.      , 0.      , 1.771875, 1.89    , 0.      ]])

请注意,代码可以对其布局进行更多优化,以便更好地理解

【讨论】:

    【解决方案2】:

    使用 numpy 的索引功能怎么样?

    arr[arr > 0] = x
    

    【讨论】:

    • 我如何自定义引用每个索引元素到其给定的行和列以获得相关的总和?
    猜你喜欢
    • 2021-04-29
    • 2018-11-09
    • 1970-01-01
    • 2015-05-10
    • 2023-03-06
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多