the else block in the following code isn't working and only the if statement is being executed to calculate the volume. What is going wrong?

Viewed 30

def volume(df):

for i in range(len(df['depth'])):
  if df['depth'][i] > 60 :
     df['volume']=df['x']*df['y']*df['z']
  else:
     df['volume'] = 8 
return df

I am working to calculate volume of a diamond dataset where dimensions x,y,z and depth are given and I have to calculate volume = xyz when depth >60 else volume is to be set to 8 but the code I have written is not assigning volume =8 when depth <60 and simply calculates volume = xyz , perhaps the code isn't taking the else condtion initially is what i thought so I used a counter a which incremented by one when else block was executed and I printed its value successfully (my debug attempt) . Can you guys help me out in this ? Thanks in advance

1 Answers

Instead of looping, try this code:

import numpy as np
df['volume']=np.where(df['depth']>60, df['x']*df['y']*df['z'], 8)
Related