python - Python中二维数组的对数

标签 python

我有一个名为矩阵的二维数组数组。其中的每个矩阵的维度都是 1000 x 1000 并且由正值组成。现在我想记录所有矩阵中的所有值(0 除外)。
我如何在 python 中轻松地做到这一点?
我有以下代码可以执行我想要的操作,但知道Python 这可以更简短:

newMatrices = []
for matrix in matrices:
    newMaxtrix = []
    for row in matrix:
        newRow = []
        for value in row:
            if value > 0:
                newRow.append(np.log(value))
            else:
                newRow.append(value)
        newMaxtrix.append(newRow)
    newMatrices.append(newMaxtrix)

最佳答案

您可以将其转换为 numpy 数组并使用numpy.log 计算值。

对于 0 值,结果将为 -Inf。之后,您可以将其转换回列表并将 -Inf 替换为 0

或者你可以在numpy中使用where

例子:

res = where(arr!= 0, log2(arr), 0)

它将忽略所有零元素。

关于python - Python中二维数组的对数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707733/

相关文章:

python - 如何使用 matplotlib 获取开始时间和结束时间高达毫秒的甘特图

python - 确定 Python 是否在 virtualenv 中运行

c++ - 将 C++ 字符串传递给 Python

python - 为什么 epoch 2 比 epoch 1 花费的时间多 18 倍?

python - 如何创建一系列单词作为超参数进行迭代?

python - 从 rpy2 传递给 R 的对象是什么?

python - AADSTS50011 : The reply URL specified in the request does not match the reply URLs configured for the application. 如何指定重定向 URI?

Python 2.7 : Code won't return answer - someone explain why?

具有否定忽略模式的python copytree

python - 在 python 中打印对象的约定