jeudi 12 août 2021

Add row to dataframe if condition is met

I have the following dataset:

dataset

If Crack == "Y", I will need to add 2 new rows using name from Outright1 and Outright2. However the position from Outright2 will be multiplied by -1.

I have applied the following method:

for i in data.index:
    if(data.Crack[i]=="Y"):
        new_row = {'Position':data['Position'][i],'Contract':data['Outright1'][i],'Outright1':np.nan,'Outright2':np.nan,'Crack':"N"}
        new_row2 = {'Position':data['Position'][i]*-1,'Contract':data['Outright2'][i],'Outright1':np.nan,'Outright2':np.nan,'Crack':"N"}
        data = data.append(new_row, ignore_index = True)
        data = data.append(new_row2, ignore_index = True)

and managed to get my desired output: desired output

However was just wondering if there is any better and more efficient way to code this?

Aucun commentaire:

Enregistrer un commentaire