本文介绍了在阵列零出低值最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,可以说,我有每个100个元素100000浮标阵。我需要值的最高X数字,但只有当它们比Y.更大的不匹配这应该被设置为0。什么是在Python这样做的最快方法的任何元素?订单必须得到维护。大部分元素都已经设定为0

样的变量:

 阵列= [0.06,0.25,0,0.15,3.5,0,0,0.04,0,0]
highCountX = 3
lowValY = 0.1

预期的结果:

 数组= [0,.25,0,0.15,3.5,0,0,0,0,0]


解决方案

这是模块。

So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0.

sample variables:

array = [.06, .25, 0, .15, .5, 0, 0, 0.04, 0, 0]
highCountX = 3
lowValY = .1

expected result:

array = [0, .25, 0, .15, .5, 0, 0, 0, 0, 0]
解决方案

This is a typical job for NumPy, which is very fast for these kinds of operations:

array_np = numpy.asarray(array)
low_values_indices = array_np < lowValY  # Where values are low
array_np[low_values_indices] = 0  # All low values set to 0

Now, if you only need the highCountX largest elements, you can even "forget" the small elements (instead of setting them to 0 and sorting them) and only sort the list of large elements:

array_np = numpy.asarray(array)
print numpy.sort(array_np[array_np >= lowValY])[-highCountX:]

Of course, sorting the whole array if you only need a few elements might not be optimal. Depending on your needs, you might want to consider the standard heapq module.

这篇关于在阵列零出低值最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 16:23
查看更多