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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With