Is there a save function in python? I want to pass SAS code in python

I want to pass SAS code in python and cannot find the save function in python.

The data is as follows:

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 sum is equal to the negative value of the previous line. So the data will look like this:

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

SAS Code:

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

Does anyone have an idea on how to do this in python? Thank!

+4
source share
1 answer

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

As an alternative:

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
+2
source

Source: https://habr.com/ru/post/1674840/


All Articles