在数组之间格式化值Numpy Python [英] Formating values in between of arrays Numpy Python
问题描述
我正在尝试编写一个函数,在该函数中检查 Numbers
元素是否在 Formatting
值之间.因此,由于 Numbers
的第一个元素不在 Formating
的第一个元素和第二个元素 0,2
之间,因此它返回0作为<代码>结果.对于 3 4>中的
3,4
元素在 2,5
之间,因此它返回那些 3,4
作为2,5之间的数字. index
的值一直递增,直到 Formating
数组的末尾.我该如何修复下面的函数,以便在没有for循环的情况下提供预期的输出.
I am trying to code a function where it checks if the Numbers
elements are between the Formating
values. So for the first element of Numbers
3 is not between the first and the second element 0, 2
of Formating
so it returns 0 as the result
. For the elements 3,4
in Numbers
are between 2 ,5
so it return those 3,4
as the numbers between 2,5. The index
value keeps on getting incremented until the end of the Formating
array. How could I fix the function below so it gives the expected output, without a for loop.
Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15, 22])
#previouse and curent index values
prevs = np.arange(0,len(Formating)-1,1)
currents = np.arange(1,len(Formating),1)
index = 0
np.where(Formating[prevs[index]] <= Numbers < Formating[currents[index]], Numbers, ++index)
预期输出:
Numbers between 0,2 = 0
Numbers between 2,5 = 3,4
Numbers between 5,12 = 5,7,8,10
Numbers between 12,15 = 0
Numbers between 15,22 = 20
推荐答案
您可以先排序再搜索排序,这样运行起来会更加高效(IO除外)
You could sort then search sorted and it will run more efficiently (except for the IO)
Numbers = np.array([3, 4, 5, 7, 8, 10,20])
Formating = np.array([0, 2 , 5, 12, 15, 22])
x = np.sort(Numbers);
l = np.searchsorted(x, Formating, side='left')
for i in range(len(l)-1):
if l[i] >= l[i+1]:
print('Numbers between %d,%d = _0_' % (Formating[i], Formating[i+1]))
else:
print('Numbers between %d,%d = %s' % (Formating[i], Formating[i+1], ','.join(map(str, list(x[l[i]:l[i+1]])))))
这篇关于在数组之间格式化值Numpy Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!