"pythonic" way to fill bag of words
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code>
There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p>

<p>I want a count for each one</p>

<pre><code>#make bag of worsds   
Word_arrayU = np.unique(Word_array)
wordBag = [['0','0'] for _ in range(len(Word_array))] #prealocate necessary space
i=0
while i&lt; len(Word_arrayU): #for each unique word
    wordBag[i][0] = Word_arrayU[i]
    #I think this is the part that takes a long time.  summing up a list comprehension with a conditional.  Just seems sloppy
    wordBag[i][1]=sum([1 if x == Word_arrayU[i] else 0 for x in Word_array])
    i=i+1
</code></pre>

<p>summing up a list comprehension with a conditional.  Just seems sloppy; is there a better way to do it?</p>

<p>Since you are already using <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html" rel="nofollow"><em>numpy.unique</em></a>, just set <em>return_counts=True</em> in the unique call:</p>

<pre><code>import numpy as np

unique,  count = np.unique(Word_array, return_counts=True)
</code></pre>

<p>That will give you two arrays, the unique elements and their counts:</p>

<pre><code>n [10]: arr = [1,3,2,11,3,4,5,2,3,4]

In [11]: unique,  count = np.unique(arr, return_counts=True)

In [12]: unique
Out[12]: array([ 1,  2,  3,  4,  5, 11])

In [13]: count
Out[13]: array([1, 2, 3, 2, 1, 1])
</code></pre>

python string counter