擅长:python、mysql、java
<p>如果速度是你想要的,那么下面的应该是相当不错的,尽管它有点复杂,因为它在numpy中使用了复数排序。这类似于在包<a href="https://github.com/ml31415/numpy-groupies" rel="nofollow">^{<cd1>}</a>中编写聚合排序方法时使用的方法(my me)。你知道吗</p>
<pre><code># get global sort order, for sorting by ID then price
full_idx = np.argsort(df['ID'] + 1j*df['price'])
# get min of full_idx for each ID (note that there are multiple ways of doing this)
n_for_id = np.bincount(df['ID'])
first_of_idx = np.cumsum(n_for_id)-n_for_id
# subtract first_of_idx from full_idx
rank = np.empty(len(df),dtype=int)
rank[full_idx] = arange(len(df)) - first_of_idx[df['ID'][full_idx]]
df['rank'] = rank+1
</code></pre>
<p>在我的机器上,5m行需要2秒,这比使用pandas的<code>groupby.rank</code>快了大约100倍(尽管我实际上没有运行5m行的pandas版本,因为它需要太长的时间;我不确定@ayhan是如何在30秒内完成的,也许是pandas版本的不同?)。你知道吗</p>
<p>如果你使用这个,那么我建议彻底测试它,因为我没有。你知道吗</p>