简体   繁体   English

如何取 numpy 数组中所有非零条目的倒数

[英]How do I take the reciprocal of all non-zero entries in a numpy array

I am trying to take the reciprocal of every non zero value in a numpy array but am messing something up.我试图取一个 numpy 数组中每个非零值的倒数,但我搞砸了。 Suppose:认为:

norm = np.arange(0,11)

I would like the np.array that would be (maintaining the zeros in place)我想要 np.array 那将是(保持零到位)

[ 0, 1, 0.5 , 0.33, 0.25, 0.2 , 0.17, 0.14, 0.12, 0.11, 0.1] 

If I set如果我设置

mask = norm !=0 

and I try我尝试

1/norm[mask]

I receive the expected result of我收到了预期的结果

[1, 0.5 , 0.33, 0.25, 0.2 , 0.17, 0.14, 0.12, 0.11, 0.1] 

However I'm trying to understand why is it that when I try the following assignment但是我试图理解为什么当我尝试以下任务时

norm[mask] = 1/norm[mask]    

i get the following numpy array.我得到以下 numpy 数组。

[0,1,0,0,0,0,0,0,0,0,0]

any ideas on why this is or how to achieve the desired np.array?关于为什么会这样或如何实现所需的 np.array 的任何想法?

Are you sure you didn't accidentally change the value of norm .您确定您没有意外更改norm的值吗?

Both两个都

mask = norm != 0
norm[mask] = 1 / norm[mask]

and

norm[norm != 0] = 1 / norm[norm != 0]

both do exactly what you want them to do.两者都做你想让他们做的事情。 I also tried it using mask on the left side and norm != 0 on the right side like you do above (why?) and it works fine.我也尝试过在左侧使用mask并在右侧使用norm != 0 ,就像你上面所做的那样(为什么?)并且它工作正常。

EDIT BY FY: I misread the example. FY 编辑:我误读了这个例子。 I thought original poster was starting with [0, .5, .333, .25] rather than with [0, 1, 2, 3, 4].我认为原始海报以 [0, .5, .333, .25] 而不是 [0, 1, 2, 3, 4] 开头。 Poster is accidentally creating an int64 array rather than a floating point array, and everything is rounding down to zero.海报意外地创建了一个 int64 数组而不是一个浮点数组,并且所有内容都向下舍入为零。 Change it to np.arange(0., 11.)将其更改为np.arange(0., 11.)

another option is using numpy.reciprocal as documented here with a parameter where as followed:另一个选项是使用numpy.reciprocal ,如此处记录的那样带有一个参数where如下所示:

import numpy as np
data = np.reciprocal(data,where= data!=0)

example:例子:

In[1]: data = np.array([2.0,4.0,0.0])
in[2]: np.reciprocal(data,where=data!=0)
Out[9]: array([0.5 , 0.25, 0.  ])

notice that this function is not intended to work with ints , therefore the initialized values are with the .0 suffix.请注意,此函数不适用于ints ,因此初始化值带有.0后缀。 if you're not sure of the type, you can always use data.astype(float64)如果您不确定类型,您可以随时使用data.astype(float64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM