dimanche 9 mai 2021

pandas - create new column based on conditional value of another coloumn

i would like to create a new column df['indexed'] based on the value of the previous row of another column (df['col2'). Except, if in row of column df['col2') is not "x" (in this example a string - date), I would like the set "100" in df['indexed']. So i expect a column "indexed" that begins every time at a value of 100, if df['col2'] is not a "x".

import pandas as pd
d = {'col1': [0.02,0.12,-0.1,0-0.07,0.01,0.02,0.12,-0.1,0-0.07,0.01],
     'col2': ['x','x','x','2021-60-30','x','x','x','x','x','x']}
df = pd.DataFrame(data=d)
df['col1'] = df['col1']+1
df['indexed'] = 0

#what i tried:
for index, row in df.iterrows():
    if row['col2'] == 'x':
        df['indexed']= df['col1'] * df['col1'].shift(1)
    else:
        df['indexed']= 100

Aucun commentaire:

Enregistrer un commentaire