【问题标题】:Apply function to all elements in NumPy matrix [duplicate]将函数应用于 NumPy 矩阵中的所有元素
【发布时间】:2019-04-20 19:26:02
【问题描述】:

假设我创建了一个 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

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

【问题讨论】:

  • 对于许多基本函数、运算符和来自它们的表达式,它只是myFunction(myMatrix)
  • 您的函数适用于整个数组。但如果该函数真的只适用于标量,则需要某种 python 循环。

标签: python python-3.x numpy matrix


【解决方案1】:

这显示了在不使用显式循环的情况下对整个 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]])

【讨论】:

  • 将数组传递给函数不会使函数在每个元素上调用,正如问题所问的那样,它确实用数组调用函数。
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 2021-09-13
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多