2013-05-02 2 views
2

이 질문은 너무 멍청 할 수도 있지만, 올바르게 수행하는 방법을 알아 내지 못했습니다.배열의 같은 요소를 계산하고 사전을 작성하십시오.

나는 주어진 배열 [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3] (0-5의 임의의 요소들)을 가지고 있고 나는 연속으로 0의 발생에 대한 카운터를 갖고 싶다.

1 times 6 zeros in a row 
1 times 4 zeros in a row 
2 times 1 zero in a row 

=> (2,0,0,1,0,1) 

그래서 사전 인덱스 및 값과 카운터 값으로서 n*0에서 이루어져있다.

최종 배열은 위와 같이 정렬되지 않은 500 만 개 이상의 값으로 구성됩니다.

+0

=> (2,0,0,1,0,1) ??? 이것은 6, 4, 1의 0으로 연속적으로 무엇을해야합니까? – dansalmo

답변

2

이 당신이 원하는 걸 얻을해야합니다

import numpy as np 

a = [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3] 

# Find indexes of all zeroes 
index_zeroes = np.where(np.array(a) == 0)[0] 

# Find discontinuities in indexes, denoting separated groups of zeroes 
# Note: Adding True at the end because otherwise the last zero is ignored 
index_zeroes_disc = np.where(np.hstack((np.diff(index_zeroes) != 1, True)))[0] 

# Count the number of zeroes in each group 
# Note: Adding 0 at the start so first group of zeroes is counted 
count_zeroes = np.diff(np.hstack((0, index_zeroes_disc + 1))) 

# Count the number of groups with the same number of zeroes 
groups_of_n_zeroes = {} 
for count in count_zeroes: 
    if groups_of_n_zeroes.has_key(count): 
     groups_of_n_zeroes[count] += 1 
    else: 
     groups_of_n_zeroes[count] = 1 

groups_of_n_zeroes 보유 :

{1: 2, 4: 1, 6: 1} 
+0

대단히 감사합니다! 실제로 그것은 많은 도움이되었습니다! – nit

0

이 몹시 복잡한 것 같다,하지만 난 찾을 수 없습니다 더 나은 아무것도 :

>>> l = [0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 0, 0, 0, 0, 1, 0, 1, 2, 1, 0, 2, 3] 

>>> import itertools 
>>> seq = [len(list(j)) for i, j in itertools.groupby(l) if i == 0] 
>>> seq 
[6, 4, 1, 1] 

>>> import collections 
>>> counter = collections.Counter(seq) 
>>> [counter.get(i, 0) for i in xrange(1, max(counter) + 1)] 
[2, 0, 0, 1, 0, 1] 
1

@ fgb 's와 유사하지만 발생 횟수를 더 많이 감안하여 취급합니다 :

items = np.array([0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3]) 
group_end_idx = np.concatenate(([-1], 
           np.nonzero(np.diff(items == 0))[0], 
           [len(items)-1])) 
group_len = np.diff(group_end_idx) 
zero_lens = group_len[::2] if items[0] == 0 else group_len[1::2] 
counts = np.bincount(zero_lens) 

>>> counts[1:] 
array([2, 0, 0, 1, 0, 1], dtype=int64) 
+0

나는이 접근법이 numpy 함수 만 사용하는 것을 좋아한다. 의견을 보내 주셔서 감사합니다. – nit

관련 문제