<p>这与被问到的<a href="https://stackoverflow.com/questions/23159791/find-the-indices-of-non-zero-elements-and-group-by-values">here</a>非常相似,所以下面是对我的答案的改编。矢量化的最简单方法是使用排序。下面的代码借鉴了即将发布的1.9版的<code>np.unique</code>实现,其中包含独特的项目计数功能,请参见<a href="https://github.com/numpy/numpy/blob/master/numpy/lib/arraysetops.py#L93" rel="noreferrer">here</a>:</p>
<pre><code>>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> sort_idx = np.argsort(a)
>>> a_sorted = a[idx]
>>> unq_first = np.concatenate(([True], a_sorted[1:] != a_sorted[:-1]))
>>> unq_items = a_sorted[unq_first]
>>> unq_count = np.diff(np.nonzero(unq_first)[0])
</code></pre>
<p>现在:</p>
^{pr2}$
<p>要获得每个值的位置索引,只需执行以下操作:</p>
<pre><code>>>> unq_idx = np.split(sort_idx, np.cumsum(unq_count))
>>> unq_idx
[array([0], dtype=int64), array([1, 4, 6], dtype=int64), array([5], dtype=int64),
array([3], dtype=int64), array([2], dtype=int64)]
</code></pre>
<p>现在可以构造字典压缩<code>unq_items</code>和{<cd3>}。在</p>
<p>注意,<code>unq_count</code>不计算最后一个唯一项的出现次数,因为拆分索引数组不需要这样做。如果你想拥有你能做到的所有价值:</p>
<pre><code>>>> unq_count = np.diff(np.concatenate(np.nonzero(unq_first) + ([a.size],)))
>>> unq_idx = np.split(sort_idx, np.cumsum(unq_count[:-1]))
</code></pre>