gpt4 book ai didi

python - NumPy 数组中负数和正数岛的计数

转载 作者:太空宇宙 更新时间:2023-11-03 14:53:39 24 4
gpt4 key购买 nike

我有一个包含大量负元素和大量正元素的数组。一个简化得多的例子是一个数组 a看起来像:array([-3, -2, -1, 1, 2, 3, 4, 5, 6, -5, -4])

(a<0).sum()(a>0).sum()给我负元素和正元素的总数,但我如何按顺序计算这些元素?我的意思是我想知道我的数组包含前 3 个负元素,6 个正元素和 2 个负元素。

这听起来像是某个地方已解决的主题,那里可能有重复的主题,但我找不到。

一个方法是使用numpy.roll(a,1)在整个数组的循环中并计算给定符号的元素数量出现在例如数组滚动时的第一个元素,但它看起来不太像 numpyic(或 pythonic),对我来说也不是很有效。

最佳答案

这是一种矢量化方法 -

def pos_neg_counts(a):
mask = a>0
idx = np.flatnonzero(mask[1:] != mask[:-1])
count = np.concatenate(( [idx[0]+1], idx[1:] - idx[:-1], [a.size-1-idx[-1]] ))
if a[0]<0:
return count[1::2], count[::2] # pos, neg counts
else:
return count[::2], count[1::2] # pos, neg counts

样本运行-

In [155]: a
Out[155]: array([-3, -2, -1, 1, 2, 3, 4, 5, 6, -5, -4])

In [156]: pos_neg_counts(a)
Out[156]: (array([6]), array([3, 2]))

In [157]: a[0] = 3

In [158]: a
Out[158]: array([ 3, -2, -1, 1, 2, 3, 4, 5, 6, -5, -4])

In [159]: pos_neg_counts(a)
Out[159]: (array([1, 6]), array([2, 2]))

In [160]: a[-1] = 7

In [161]: a
Out[161]: array([ 3, -2, -1, 1, 2, 3, 4, 5, 6, -5, 7])

In [162]: pos_neg_counts(a)
Out[162]: (array([1, 6, 1]), array([2, 1]))

运行时测试

其他方法-

# @Franz's soln        
def split_app(my_array):
negative_index = my_array<0
splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
len_list = [len(i) for i in splits]
return len_list

更大数据集上的时间 -

In [20]: # Setup input array
...: reps = np.random.randint(3,10,(100000))
...: signs = np.ones(len(reps),dtype=int)
...: signs[::2] = -1
...: a = np.repeat(signs, reps)*np.random.randint(1,9,reps.sum())
...:

In [21]: %timeit split_app(a)
10 loops, best of 3: 90.4 ms per loop

In [22]: %timeit pos_neg_counts(a)
100 loops, best of 3: 2.21 ms per loop

关于python - NumPy 数组中负数和正数岛的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44384687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com