在阵列零出低值最快的方法?

编程入门 行业动态 更新时间:2024-10-25 22:34:27
本文介绍了在阵列零出低值最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

样的变量:

阵列= [0.06,0.25,0,0.15,3.5,0,0,0.04,0,0]highCountX = 3lowValY = 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.

更多推荐

在阵列零出低值最快的方法?

本文发布于:2023-11-02 08:04:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551832.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阵列   最快   低值   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!