用最接近的非NaN值替换NumPy数组中的NaN [英] Replace NaN's in NumPy array with closest non-NaN value

查看:142
本文介绍了用最接近的非NaN值替换NumPy数组中的NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NumPy数组a,如下所示:

I have a NumPy array a like the following:

>>> str(a)
'[        nan         nan         nan  1.44955726  1.44628034  1.44409573\n  1.4408188   1.43657094  1.43171624  1.42649744  1.42200684  1.42117704\n  1.42040255  1.41922908         nan         nan         nan         nan\n         nan         nan]'

我想用最接近的非NaN值替换每个NaN,以便将开头的所有NaN都设置为1.449...,而结尾的所有NaN都设置为1.419....

I want to replace each NaN with the closest non-NaN value, so that all of the NaN's at the beginning get set to 1.449... and all of the NaN's at the end get set to 1.419....

我可以看到如何针对像这样的特定情况执行此操作,但是我需要能够对任意长度的数组进行一般操作,并且在数组的开头和结尾都应具有任意长度的NaN(不会有NaN位于数字中间).有什么想法吗?

I can see how to do this for specific cases like this, but I need to be able to do it generally for any length of array, with any length of NaN's at the beginning and end of the array (there will be no NaN's in the middle of the numbers). Any ideas?

通过np.isnan()我可以很容易地找到NaN,但是我无法弄清楚如何获得与每个NaN最接近的值.

I can find the NaN's easily enough with np.isnan(), but I can't work out how to get the closest value to each NaN.

推荐答案

我想用最接近的非NaN值替换每个NaN ...在数字中间没有NaN's

I want to replace each NaN with the closest non-NaN value... there will be no NaN's in the middle of the numbers

以下将执行此操作:

ind = np.where(~np.isnan(a))[0]
first, last = ind[0], ind[-1]
a[:first] = a[first]
a[last + 1:] = a[last]

这是直接的numpy解决方案,不需要Python循环,不需要递归,不需要列表推导等.

This is a straight numpy solution requiring no Python loops, no recursion, no list comprehensions etc.

这篇关于用最接近的非NaN值替换NumPy数组中的NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆