[英]Update last element of each row in numpy array
I have two numpy arrays, array_one
which is NxM and array_two
which is NxMx3, and I'd like to change the value of the last element in each row of array_two
, based on values from array_one
, like this:我有两个 numpy arrays, array_one
是 NxM 和array_two
是 NxMx3,我想根据array_one
的值更改array_two
每一行中最后一个元素的值,如下所示:
array_two[i, j, -1] = foo(array_one[i,j])
where foo
returns a value based on a computation on an element from array_one
.其中foo
基于对来自array_one
的元素的计算返回一个值。
Is there a way to avoid manually looping over the arrays and speed up this process using numpy functions?有没有办法避免手动循环 arrays 并使用 numpy 函数加快此过程?
Example showing use of np.vectorize to achieve what you had in mind.示例显示使用 np.vectorize 来实现您的想法。
replace square with your foo and you should be in business.用你的 foo 替换 square ,你应该做生意了。
import numpy as np
array_3d = np.ones((2,3,2))
array_2d = np.random.randn(2,3)
def square(x):
return x**2
square_all = np.vectorize(square)
array_3d[:,:,-1] = square_all(array_2d)
print(f'{array_3d[:,:,:]=}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.