绝对最多2个numpy数组

2024-10-02 12:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

这似乎很明显,但它暗指我:我想用numpy.maximum转换下面的代码,以便在数组上更有效地计算:

P = np.random.uniform(low=-10, high=10, size=(30,))
for i in range(P.shape[0]): #for element in array
 print max(P[i], np.ones(P.shape[0])[i], key=abs) #take the absolute max

更有效的版本是使用:

^{pr2}$

但是我如何计算这个绝对值,同时保留符号呢?在


Tags: 代码innumpyforsizenprandomuniform
1条回答
网友
1楼 · 发布于 2024-10-02 12:29:38

使用np.where;绝对值作为条件,原始值作为返回元素:

np.where(np.abs(P) > 1, P, 1)

#array([ 7.91709218, -5.8691354 ,  2.10242613,  3.0050441 ,  1.12334666,
#        3.98891018,  3.60936593, -6.3196432 ,  1.        ,  9.58885417,
#       -2.13595449,  1.49568368, -2.93928838, -7.01366456, -9.1816925 ,
#        4.48940296, -2.3597295 ,  8.66614578, -9.95693121,  8.61132135,
#       -6.24103691,  1.        ,  5.55632026,  4.00445283,  1.        ,
#       -5.17295561,  1.        ,  1.        , -2.94661818,  4.45517007])

相关问题 更多 >

    热门问题