什么是在numpy数组上映射函数的最有效方法?我目前正在执行以下操作:
import numpy as np
x = np.array([1, 2, 3, 4, 5])
# Obtain array of square of each element in x
squarer = lambda t: t ** 2
squares = np.array([squarer(xi) for xi in x])
然而,这种方法可能非常低效,因为我使用列表推导式在将新数组构建为Python列表之前,再将其转换回numpy数组。我们能做得更好吗?
squarer(x)
怎么样? - Lifesquarer(x)
将在数组元素上应用squarer
函数,并返回一个包含单个squarer(element)
调用结果的数组。我写这篇文章是因为一开始“只有 squarer(x)”并不够清晰。 - JustAnEuropean