如何在Python中按组执行proc等级(SAS函数)?

时间:2019-05-28 07:24:05

标签: python sas

我想在Python中复制以下SAS代码。

proc rank data=a out=b ties=low;    
by id code date; 
var key_id;
ranks rank;   
run;

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

a = pd.DataFrame({'id': [0,1,1,2,2],
                  'code': ['a','b','b','c','c'],
                  'date':[-5,-4,-4,-2,-2],
                  'key_id':[0.05,3,5,0.001,-1]})

b =a.groupby(['id', 'code', 'date'])['key_id'].rank(ascending=True)
a['rank'] = b
a