擅长:python、mysql、java
<p>你可以这样做:</p>
<pre><code>df['rn'] = (df.sort_values(['price'], ascending=False)
.groupby('currency').cumcount() + 1
)
qry = (select_number
.reset_index()
.astype(str)
.apply(lambda x: '((currency=="{0[0]}") & (rn<={0[1]}))'.format(x), axis=1)
.str.cat(sep=' | ')
)
print(df.query(qry))
</code></pre>
<p>输出</p>
<pre><code>In [147]: df.query(qry)
Out[147]:
price currency rn
id
4 1750 EU 2
8 4000 EU 1
1 1000 GBP 2
9 1400 GBP 1
6 7000 USD 1
</code></pre>
<p>说明:</p>
<p><code>rn</code>-是每个分区/组的辅助列-行数,按<code>price</code>(在该组内)降序排序</p>
<p><code>qry</code>-是动态生成的查询</p>
<pre><code>In [149]: qry
Out[149]: '((currency=="EU") & (rn<=2)) | ((currency=="GBP") & (rn<=2)) | ((currency=="USD") & (rn<=1))'
</code></pre>