[英]Identify groups of consecutive values within NumPy array
I have a NumPy array of values, and I am needing to identify groups of consecutive values within the array. 我有一个NumPy值数组,我需要识别数组中的连续值组。
I've tried writing a "for" loop to do this, but I'm running into a host of issues. 我尝试编写一个“ for”循环来执行此操作,但是我遇到了很多问题。 So I've looked at the documentation for groupby in itertools. 因此,我在itertools中查看了groupby的文档。 I've never used this before, and I'm more than a little confused by the documentation, so here I am. 我以前从未使用过它,并且我对文档感到有些困惑,所以我来了。
Could someone give a more "layman speak" explanation of how to use groupby? 有人可以对使用groupby进行更“外行讲话”的解释吗? I don't need a sample code, per se, just a more thorough explanation of the documentation. 本质上,我不需要样本代码,而只是对文档的更详尽的解释。
a good answer to this is to use a generator to group it (might not be the fastest method) 一个很好的答案是使用生成器对其进行分组(可能不是最快的方法)
def groupings(a):
g = []
for val in a:
if not g:
g.append(val)
elif abs(g[-1] - val) <= 1.00001:
g.append(val)
else:
yield g
g = []
print list(groupings(my_numpy_array))
I know this doesnt give you a laymans explanation of group by (group consecutive items that match some criteria... it would be somewhat painful for this type of application) 我知道这不会给您一个通俗易懂的分组依据说明(符合某些条件的分组连续项目...对于这种类型的应用程序来说会有些痛苦)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.