在阵列零出低值最快的方法? [英] Fastest way to zero out low values in array?

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

问题描述

因此​​,可以说,我有每个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]


解决方案

这是 numpy的,这是这些类型的操作非常快:

  array_np = numpy.asarray(阵列)
low_values​​_indices = array_np< lowValY#当值较低
array_np [low_values​​_indices] = 0#所有低值设置为0

现在,如果你只需要highCountX最大的元素,你甚至可以忘记小分子(而不是将它们设置为0,对它们进行排序)和大元素只排序列表:

  array_np = numpy.asarray(阵列)
打印numpy.sort(array_np [array_np> = lowValY]) - highCountX:]

当然,排序整个数组,如果你只需要几个因素可能不是最佳。根据你的需求,你可能要考虑的标准 heapq 模块。

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.

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

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