name = 'Coupon_id' # 折扣率排序 datas[name_prifix + 'discount_rateRank'] = datas.groupby(name)['discount_rate'].rank(ascending = False) datas[name_prifix + 'discount_rateRankAscend'] = datas.groupby(name)['discount_rate'].rank(ascending = True) # 距离排序 datas[name_prifix + 'distanceRank'] = datas.groupby(name)['Distance'].rank(ascending = False) datas[name_prifix + 'distanceRankAscend'] = datas.groupby(name)['Distance'].rank(ascending = True) # 领券日期排序 datas[name_prifix + 'date_receivedRank'] =datas.groupby(name)['Date_received'].rank(ascending = False) datas[name_prifix + 'date_receivedRankAscend'] =datas.groupby(name)['Date_received'].rank(ascending = True) 请帮我用groupby函数改写
时间: 2024-02-05 10:02:25 浏览: 70
vb_QRCode_EWM.rar
Sure! 这段代码可以使用 `groupby` 函数进行改写,如下所示:
```
cols_to_rank = ['discount_rate', 'Distance', 'Date_received']
grouped = datas.groupby(name)
for col in cols_to_rank:
datas[name_prifix + col + 'Rank'] = grouped[col].rank(ascending=False)
datas[name_prifix + col + 'RankAscend'] = grouped[col].rank(ascending=True)
```
这样,我们可以避免重复代码并且更加简洁明了。
阅读全文