Quickly convert numpy arrays with index to dict of numpy arrays keyed on that index
<p>I have a set of numpy arrays. One of these is a list of "keys", and I'd like to rearrange the arrays into a dict of arrays keyed on that key. My current code is:</p>

<pre><code>for key, val1, val2 in itertools.izip(keys, vals1, vals2):
    dict1[key].append(val1)
    dict2[key].append(val2)
</code></pre>

<p>This is pretty slow, since the arrays involved are millions of entries long, and this happens many times. Is it possible to rewrite this in vectorized form? The set of possible keys is known ahead of time, and there are ~10 distinct keys.</p>

<p><strong>Edit:</strong> If there are k distinct keys and the list is n long, the current answers are O(nk) (iterate once for each key) and O(n log n) (sort first). I'm still looking for an O(n) vectorized solution, though. This is hopefully possible; after all, the easiest possible nonvectorized thing (i.e. what I already have) is O(n).</p>

<p>The vectorized way to do this is probably going to require you to sort your keys. The basic idea is that you sort the keys and vals to match. Then you can split the val array every time there is a new key in the sorted keys array. The vectorized code looks something like this:</p>

<pre><code>import numpy as np

keys = np.random.randint(0, 10, size=20)
vals1 = np.random.random(keys.shape)
vals2 = np.random.random(keys.shape)

order = keys.argsort()
keys_sorted = keys[order]

# Find uniq keys and key changes
diff = np.ones(keys_sorted.shape, dtype=bool)
diff[1:] = keys_sorted[1:] != keys_sorted[:-1]
key_change = diff.nonzero()[0]
uniq_keys = keys_sorted[key_change]

vals1_split = np.split(vals1[order], key_change[1:])
dict1 = dict(zip(uniq_keys, vals1_split))

vals2_split = np.split(vals2[order], key_change[1:])
dict2 = dict(zip(uniq_keys, vals2_split))
</code></pre>

<p>This method has complexity O(n * log(n)) because of the argsort step. In practice, argsort is very fast unless n is very large. You're likely going to run into memory issues with this method before argsort gets noticeably slow.</p>

python numpy vectorization