我有一个名为矩阵的二维数组数组。其中的每个矩阵的维度都是 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/