jeudi 15 mars 2018

using previous row value by looping through index conditioning

If I have a data:

data = {'x':[1,2,3,4,5]} df=pd.DataFrame(data) display (df)

I want to make a new column x_new but I want the first row of this new column to be set to a specific number (let say -2). Then from 2nd row, use the previous row to iterate through the cx function

def cx(x): if df.loc[1,'x_new']==0: df.loc[1,'x_new']= -2 else: x_new = x + 2 return x_new

df['x_new']=(cx(df['x']))

The final dataframe

I am not sure on how to do this. Thank you for your help

Aucun commentaire:

Enregistrer un commentaire