One vectorized
接近与np.unique and np.searchsorted -
# Get unique elements and their counts
unq,counts = np.unique(a,return_counts=True)
# Get the positions of unique elements in a.
# Use those positions to index into counts array for final output.
out = counts[np.searchsorted(unq,a.ravel())]
样本运行 -
In [86]: a
Out[86]: array([[1, 1, 4, 1, 4, 3, 1]])
In [87]: out
Out[87]: array([4, 4, 2, 4, 2, 1, 4])
根据@Jaime 的评论,您可以使用np.unique
像这样独自一人——
_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True)
out = counts[inv_idx]