There's no such thing as a 'tab separated array'. The display of r is consistent with it being a numpy array (as is the error message). It may have been loaded from a tab separated CSV. In any case, count is a list method, not an array one. Either convert it to a list, or use one of the iterative solutions.
There is an array bincount. Since your array appears to be integers in a reasonable range, e.g. 0-1000), it might apply here.
Make a sample array:
In : r=np.random.randint(0,1000,2000)
In : r
Out: array([170, 754, 151, ..., 115, 299, 879])
Its str display is:
In : print(r)
[170 754 151 ..., 115 299 879]
This probably confuses Python programmers who don't know about numpy.
bincount finds the count for all values in the range:
I probably should have used np.bincount(r,minlength=1000).
The 7th value in that count list is 4, so let's select that:
In : np.bincount(r,minlength=1000)
I can use count if I first convert r to a list:
In : r.tolist().count(6)
The iterative solutions also work, but are slower:
for i in r:
In : foo(r,6)
In : timeit foo(r,6)
1000 loops, best of 3: 983 us per loop
In : timeit len([i for i in r if i==6])
1000 loops, best of 3: 985 us per loop
In : timeit r.tolist().count(6)
10000 loops, best of 3
Asked in February 2016Viewed 1,833 timesVoted 13Answered 5 times