对数组的行进行向量化
我有一个数组 X
,我想将函数 f
应用于 X
的所有行:
# silly example
X = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]], 'i')
def f(row): return sum(row)
y = numpy.vectorize(f, 'i')(rows(X))
现在,y
> 应该是array([15,30], 'i')
。哪种方法或切片魔法能够以最有效的方式实现行?
I have an array X
and I want to apply a function f
to all the rows of X
:
# silly example
X = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]], 'i')
def f(row): return sum(row)
y = numpy.vectorize(f, 'i')(rows(X))
Now, y
should be array([15,30], 'i')
. Which method or slicing magic will implement rows
in the most efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NumPy 实现了“特定轴上的动作”的概念。通用函数为
numpy.apply_along_axis()
:(其中
sum
当然可以替换为任何内容)。NumPy implements the concept of "action over a particular axis". The general function is
numpy.apply_along_axis()
:(where
sum
can of course be replaced by anything).它必须是 numpy 提供的东西吗?因为我只看到列表理解
Does it have to be something provided by numpy? Because I just see a list comprehension
这是另一个例子,它考虑了结果的类型和大小:
即使循环不是 C 循环,设置结果的类型和大小可能有助于加快速度。
Here is another shot at it, which takes into account the type and size of the result:
Even though the loop is not a C loop, setting the type and size of the result might help speed things up.