python - 将函数应用于 NumPy 矩阵中的所有元素

标签 python python-3.x numpy matrix

假设我创建了一个 3x3 NumPy 矩阵。将函数应用于矩阵中的所有元素(如果可能的话,无需循环遍历每个元素)的最佳方法是什么?

import numpy as np    

def myFunction(x):
return (x * 2) + 3

myMatrix = np.matlib.zeros((4, 4))

# What is the best way to apply myFunction to each element in myMatrix?

编辑:如果该函数是矩阵友好的,那么当前提出的解决方案效果很好,但是如果它是这样一个仅处理标量的函数呢?

def randomize():
    x = random.randrange(0, 10)
    if x < 5:
        x = -1
    return x

唯一的方法是循环遍历矩阵并将函数应用于矩阵内的每个标量吗?我不是在寻找特定的解决方案(例如如何随机化矩阵),而是在矩阵上应用函数的通用解决方案。希望这有帮助!

最佳答案

这显示了在不使用显式循环的情况下对整个 Numpy 数组进行数学运算的两种可能方法:

import numpy as np                                                                          

# Make a simple array with unique elements
m = np.arange(12).reshape((4,3))                                                            

# Looks like:
# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11]])

# Apply formula to all elements without loop
m = m*2 + 3

# Looks like:
# array([[ 3,  5,  7],
#       [ 9, 11, 13],
#       [15, 17, 19],
#       [21, 23, 25]])

# Define a function
def f(x): 
   return (x*2) + 3 

# Apply function to all elements
f(m)

# Looks like:
# array([[ 9, 13, 17],
#       [21, 25, 29],
#       [33, 37, 41],
#       [45, 49, 53]])

关于python - 将函数应用于 NumPy 矩阵中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53357638/

相关文章:

python - 如何在Python中填写插入语句的列名

python - 无法在 Python 中为非平方整数编码

python - numpy 基于 Mx1 矩阵创建 Mx2 矩阵

python - 如何在 matlab 和 python 中重现相同的随机整数数组?

python - 通过 makepy 添加了 AutoCAD 的 typelib,现在 win32com 不适用于 AutoCAD

Python 使用 exec 从 local() 调用函数目录

python - 是否提供包含英文单词(包括频率)的列表?

algorithm - 如何在编码算法中存储 PIN 码? python 3

python - 正则表达式 - 在文本中搜索相似的国家名称

python - 使用索引和 bool 选择后更新二维矩阵上的值