本文介绍了计算一个numpy数组中一行中重复元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种执行以下操作的快速方法:说我有一个数组
I'm looking for a quick way to do the following:Say I have an array
X = np.array([1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5])
我正在寻找连续的频率,而不是简单的元素频率.因此,第一个1重复3次,而不是2 5次,而不是3 2次,依此类推.因此,如果freq
是我的函数,则为:
Instead of a simple frequency of elements I'm looking for the frequency in a row. So first 1 repeats 3 times, than 2 5 times, than 3 2 times , etc. So if freq
is my function than:
Y = freq(X)
Y = np.array([[1,3],[2,5],[3,2],[1,2],[0,3],[5,1]])
例如,我可以这样编写循环:
For example, I can write this with loops like this:
def freq(X):
i=0
Y=[]
while i<len(X):
el = X[i]
el_count=0
while X[i]==el:
el_count +=1
i+=1
if i==len(X):
break
Y.append(np.array([el,el_count]))
return np.array(Y)
我正在寻找一种更快,更好的方法.谢谢!
I'm looking for a faster and nicer way to do this.Thanks!
推荐答案
您可以使用itertools.groupby
来执行操作,而无需调用numpy
.
You can use itertools.groupby
to perform the operation without invoking numpy
.
import itertools
X = [1,1,1,2,2,2,2,2,3,3,1,1,0,0,0,5]
Y = [(x, len(list(y))) for x, y in itertools.groupby(X)]
print(Y)
# [(1, 3), (2, 5), (3, 2), (1, 2), (0, 3), (5, 1)]
这篇关于计算一个numpy数组中一行中重复元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!