简体   繁体   中英

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?

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 = x y z 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 = x y z , 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

Instead of looping, try this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM