Python的code对数组计数过零数 [英] Python code for counting number of zero crossings in an array

查看:393
本文介绍了Python的code对数组计数过零数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待计数极性阵列变化的时代价值数(编辑:次数在数组中值交叉零)。

I am looking to count the number of times the values in an array change in polarity ( Number of times the values in an array cross zero).

假设我有一个数组:

[80.6  120.8  -115.6  -76.1  131.3  105.1  138.4  -81.3
 -95.3  89.2  -154.1  121.4  -85.1  96.8  68.2]`

我要计数为8。

一种解决方案是运行一个循环,并检查其大于或小于0,并保持previous极性的历史。

One solution is to run a loop and check for greater than or less than 0, and keep a history of the previous polarity.

我们能做到这一点更快?

Can we do this faster?

编辑:我的目的是真正更快地找到的东西,因为我有长度的这些阵列周围68554308,我必须做100+这种阵列这些计算。

My purpose is really to find something faster, because I have these arrays of length around 68554308, and I have to do these calculations on 100+ such arrays.

推荐答案

这产生相同的结果:

import numpy as np
my_array = np.array([80.6, 120.8, -115.6, -76.1, 131.3, 105.1, 138.4, -81.3, -95.3,  
                     89.2, -154.1, 121.4, -85.1, 96.8, 68.2])
((my_array[:-1] * my_array[1:]) < 0).sum()

给出了:

8

和似乎是最快的解决方案:

and seems to be the fastest solution:

%timeit ((my_array[:-1] * my_array[1:]) < 0).sum()
100000 loops, best of 3: 11.6 µs per loop

相比,以最快至今:

Compared to the fastest so far:

%timeit (np.diff(np.sign(my_array)) != 0).sum()
10000 loops, best of 3: 22.2 µs per loop

也为更大的阵列:

Also for larger arrays:

big = np.random.randint(-10, 10, size=10000000)

这样的:

%timeit ((big[:-1] * big[1:]) < 0).sum()
10 loops, best of 3: 62.1 ms per loop

VS

%timeit (np.diff(np.sign(big)) != 0).sum()
1 loops, best of 3: 97.6 ms per loop

这篇关于Python的code对数组计数过零数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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