[英]Loop over elements in a numpy array of arbitrary dimension
I have a code like the following:我有如下代码:
def infball_proj(mu, beta):
newmu = np.zeros(mu.shape)
if len(mu.shape) == 2:
for i in range(mu.shape[0]):
for j in range(mu.shape[1]):
if np.abs(mu[i,j]) > beta:
newmu[i,j] = np.sign(mu[i,j]) * beta
else:
newmu[i,j] = mu[i,j]
return newmu
elif len(mu.shape) == 1:
for i in range(mu.shape[0]):
if np.abs(mu[i]) > beta:
newmu[i] = np.sign(mu[i]) * beta
else:
newmu[i] = mu[i]
return newmu
Is there a smarter way to do this so I don't have to write the 2 different cases?有没有更聪明的方法来做到这一点,所以我不必编写 2 个不同的案例? It would be nice if I could have a version that scales to an arbitrary dimension (ie numbers of axes).
如果我可以有一个可以缩放到任意维度(即轴数)的版本,那就太好了。
Something like this should do the job:这样的事情应该可以完成这项工作:
newmu = np.where(np.abs(mu) > beta, np.sign(mu) * beta, mu)
Or, if I get the logic right,或者,如果我的逻辑正确,
newmu = np.minimum(np.abs(mu), beta) * np.sign(mu)
mu[np.abs(mu)>beta] = np.sign(mu[np.abs(mu)>beta]) * beta
np.abs(mu)>beta
will create a boolean array which can then be used for boolean indexing . np.abs(mu)>beta
将创建一个布尔数组,然后可用于布尔索引。
The LHS mu[np.abs(mu)>beta]
will return a view of the elements being selected by the boolean indexing and can be assigned to the value your want, that is, the RHS. LHS
mu[np.abs(mu)>beta]
将返回由布尔索引选择的元素的视图,并且可以分配给您想要的值,即 RHS。
REMEMBER : Try to avoid for-loop of NumPy array as it is very inefficient.记住:尽量避免 NumPy 数组的 for 循环,因为它非常低效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.