0

If product type == option, I replace the value in the PRICE column with the value of the STRIKE column.

How can I do this without using the for loop? (to make it faster)

Now I have the following but it's slow:

for i in range(df.shape[0]):
   if df.loc[i,'type'] == 'Option:
       df.loc[i,'PRICE'] = df.loc[i,'STRIKE']

2 Answers2

1

Use .loc in a vectorized fashion

df.loc[df['type'] == 'Option', 'PRICE'] = df['STRIKE']
Corralien
  • 109,409
  • 8
  • 28
  • 52
0
mask = (df.type == 'Option')
df[mask].PRICE = df[mask].STRIKE

see: https://www.geeksforgeeks.org/boolean-indexing-in-pandas/

honi
  • 946
  • 1
  • 7
  • 18
  • `df[mask].PRICE` is not safe because you're not guaranteed that `df[mask]` will return a view and not a copy and so the potential for failure to update exists as if `df[mask]` returns a copy the updated values will not be reflected in `df`. – Henry Ecker Oct 11 '21 at 21:10