简体   繁体   English

numpy数组过滤器并替换

[英]numpy array filter and replace

I have an array 我有一个数组

a = np.array([1,2,3,4,np.nan])

I would like to replace anything which is less than 1.5 by np.nan , ie I would like 我想用np.nan替换所有小于1.5的np.nan ,即我想

a = np.array([np.nan,2,3,4,np.nan])

how do I do that? 我怎么做?

I did 我做了

 a[a<1.5] = np.nan

I got the following run time warning error in IPython (Py3.4) RuntimeWarning: invalid value encountered in less . 我在IPython(Py3.4) RuntimeWarning: invalid value encountered in less收到以下运行时警告错误RuntimeWarning: invalid value encountered in less Is this because my list had np.nan ? 这是因为我的列表中np.nan吗? Is there anything I can do to prevent this? 我有什么办法可以防止这种情况发生?

Also is there a way doing this inline without assigning? 还有一种无需分配就可以内联的方式吗? Instead of doing 而不是做

a[a<1.5]=np.nan 
return a 

I can just do 我可以做

 return a... 

where that .... is something that need filling in. ....是需要填写的地方。

Is this [ RuntimeWarning ] because my list had np.nan? 这是[ RuntimeWarning ],因为我的列表包含np.nan吗?

Yes. 是。

Is there anything I can do to prevent this? 我有什么办法可以防止这种情况发生?

In your case, this warning can be safely ignored. 就您而言,可以安全地忽略此警告。 So that you don't accidentally suppress unrelated warnings, please don't put anything else inside the context manager besides the one line shown . 为了避免意外删除无关的警告,请不要在上下文管理器中放入除显示的那一行以外的任何内容

>>> import numpy as np
>>> a = np.array([1,2,3,4,np.nan])
>>> with np.errstate(invalid='ignore'):
...     a[a<1.5] = np.nan
...     
>>> a
array([ nan,   2.,   3.,   4.,  nan])

This operates in-place, a copy is not created here. 这是就地操作,此处未创建副本。 To return a copy, with the original a unmodified, prefer the masked array approach . 要返回副本,与原来的a修改,喜欢蒙面阵列的方法

Another option that gets you to your return statement as desired: 另一种选择可让您根据需要进入return语句:

mask = ~np.isnan(a)
mask[mask] &= a[mask] < 1.5
return np.where(mask, np.nan, a)

Example: 例:

def ma_lessthan(arr, num):
    mask = ~np.isnan(arr)
    mask[mask] &= arr[mask] < num
    return np.where(mask, np.nan, arr)

print(ma_lessthan(a, 1.5))
[ nan   2.   3.   4.  nan]

mask credit to: @Jaime . mask 致谢@Jaime

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

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