Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a retain function in python? I want to transfer SAS code to python

Tags:

python

pandas

sas

I want to transfer SAS code to python, and cannot find a retain function in python.

The data is like :

type_id    amount
1           100
1           200
1           400
2           0
1           200
1           300
2           0
1           150

What I want is when type_id = 2, the amount is equal to the negative value of the previous row. So the data will be like this after retain function:

type_id    amount
1           100
1           200
1           400
2          -400
1           200
1           300
2          -300
1           150

The SAS code is :

data B;
set A;
retain tempvar 0;
if type_id = 2
then amount = tempvar;
else tempvar = -amount;
drop tempvar;
run;

Does anyone have any idea about how to do this in python? Thanks!

like image 455
juanbin Avatar asked Oct 18 '22 14:10

juanbin


1 Answers

IIUC

df
type_id amount
0   1   100
1   1   200
2   1   400
3   2   0
4   1   200
5   1   300
6   2   0
7   1   150

def retain(df):
    df['ret'] = df['amount'].shift()
    df.ix[df['type_id']==2,'amount'] = -df.ix[df['type_id']==2,'ret']
    df.drop("ret", axis=1, inplace=True)
    return df

retain(df)
type_id amount
0   1   100.0
1   1   200.0
2   1   400.0
3   2   -400.0
4   1   200.0
5   1   300.0
6   2   -300.0
7   1   150.0

Alternatively:

def retain(df):
    df.amount.ix[df.type_id==2] = - df.amount.shift().ix[df.type_id==2]
    return df

retain(df)
type_id amount
0   1   100.0
1   1   200.0
2   1   400.0
3   2   -400.0
4   1   200.0
5   1   300.0
6   2   -300.0
7   1   150.0
like image 84
Sergey Bushmanov Avatar answered Oct 20 '22 09:10

Sergey Bushmanov