python - Counting same elements in an array and create dictionary -
this question might noob, still not able figure out how properly.
i have given array [0,0,0,0,0,0,1,1,2,1,0,0,0,0,1,0,1,2,1,0,2,3
] (arbitrary elements 0-5) , want have counter occurence of zeros in row.
1 times 6 zeros in row 1 times 4 zeros in row 2 times 1 0 in row => (2,0,0,1,0,1)
so dictionary consists out of n*0
values index , counter value.
the final array consists of 500+ million values unsorted 1 above.
this should want:
import numpy np = [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 zeroes index_zeroes = np.where(np.array(a) == 0)[0] # find discontinuities in indexes, denoting separated groups of zeroes # note: adding true @ end because otherwise last 0 ignored index_zeroes_disc = np.where(np.hstack((np.diff(index_zeroes) != 1, true)))[0] # count number of zeroes in each group # note: adding 0 @ start first group of zeroes counted count_zeroes = np.diff(np.hstack((0, index_zeroes_disc + 1))) # count number of groups same number of zeroes groups_of_n_zeroes = {} 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
holds:
{1: 2, 4: 1, 6: 1}
Comments
Post a Comment