如何在数组中找到最接近的值

时间:2016-02-12 17:30:00

标签: python python-2.7 numpy

我有以下数组:

y_new = [0.0057602140000000005, nan, nan, nan, nan, nan, 0.0057104540000000002, nan, 0.0056821390000000001, nan, nan, nan, nan, nan, nan, 0.0056911319999999998, nan, nan, nan, nan, nan, 0.0054902060000000001, nan, nan, nan, nan, nan, nan, 0.0053461740000000004, nan, nan, nan, nan, 0.0055180319999999991, nan, nan, nan, nan, nan, nan, nan, 0.0051784170000000003, nan, nan, nan, nan, nan, nan, 0.0051544399999999997, nan, nan, nan, nan, nan, nan, 0.005136781, nan, nan, 0.0051989519999999997, nan, nan, nan, nan, nan, nan, 0.0051330490000000006, 0.0052893050000000002, nan, nan, nan, nan, nan, nan, nan, 0.0053077380000000002, nan, nan, nan, nan, 0.0053766209999999998, 0.0053431900000000003, nan, nan, nan, nan, 0.0051352960000000001]

我想在该数组中选择一个随机点,并找出最近的实际值高于或低于它的位置。非实数值是“nan”,实际值是数字。然后,我想计算这两个点之间的间距差异,其中y_new[5]y_new[6]之间的差异仅为1天。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我不是一个python程序员,但我认为类似的东西会给你你想要的东西。

randomIndex = 5;
sizeofArray = 200;
lessThan = 0;
greaterThan = 0;

for(int i = randomIndex; i >=0; i---)
{
value = y_new[i];
if(value != nan)
{
lessThan = i;
return;
} 

}

for(int i = randomIndex; i <sizeOfArray; i++)
{
value = y_new[i];
if(value != nan)
{
greaterThan = i;
return;
} 

}

less = randomIndex - lessThan;
great = greaterThan - randomIndex;

if(less < great) return less;
else return great

答案 1 :(得分:0)

这是我认为最狡猾的方式......

假设索引为随机索引, y_new一个简化的数组, 诀窍就是拆分你的清单(带切片) 并在正常和反向列表中找到下一个实数。 然后将查找th delta的索引求和。 希望它有所帮助。

这是一个简单的代码:

index=4
y_new = [0.1, 'nan', 'nan', 0.2, 'nan','nan', 0.3,'nan']

nextList=y_new[index:]
beforeList=y_new[:index]

before_idx=(i for i,v in enumerate(list(reversed(beforeList))) if v!='nan').next()    
next_idx=(i for i,v in enumerate(nextList) if v!='nan').next()    

print y_new
print before_idx
print next_idx

print "interval between 2 real number near index %d is: %d days" %(index,(next_idx+before_idx+1))