Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform proc rank (SAS function) within by groups in Python?

Tags:

python

sas

I want to replicate the following SAS code in Python.

proc rank data=a out=b ties=low;    
by id code date; 
var key_id;
ranks rank;   
run;
like image 710
Nelwin Jacob Avatar asked Apr 15 '26 11:04

Nelwin Jacob


1 Answers

I would do something like this:

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
like image 89
Altons Avatar answered Apr 18 '26 02:04

Altons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!