简体   繁体   中英

How to use an if, else statement inside of a while loop that reads a series of values from a variable for calculations

I am very new to using python and am trying to perform a calculation for an equation. I need to perform the calculation 6 times and the input data is in the form of series (EX. the variable wi contains a series of 6 values). The equation in question has two different forms, 1 if wi is less than or equal to.49 it takes form A, and if wi is greater than.49 it takes form B.

I was trying to use a while loop to complete the necessary calculations with an embedded if-else statement to take the proper form of the equation with each iteration. The variable I was trying to place the results in is aai and I made an array for it as well with zeros as place holders. I get the error "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" when trying to run the code. The code I have is pasted below. Is it possible to do this or do I need to individually write out each variable (EX. wi = (0,1,2....) to wi0=0 , wi1=1 , wi2=2 and make a number of loops for each? Thank you for all of your time and help in this matter. Sincerely, Jace

import numpy as np
import pandas as pd

f = pd.read_excel (r"C:\Users\jmmar\Documents\PNG480MAT.xlsx")
#ex = pd.DataFrame(e)

t = 200
R= 10.73
mw = f.iloc[0,:]
tci = f.iloc[1,:]
pci = f.iloc[2,:]
zci= f.iloc[3,:]
wi = f.iloc[4,:]
omai = f.iloc[5,:]
ombi = f.iloc[6,:]
tri = t/tci
n=0
aai = np.zeros(6)
while n<7  :
   if wi.le(wi,.49) :
      fwi = .374640+1.54226*wi-.26992*wi**2
      n+1
        
   else :
       fwi = .379642+1.48503*wi-.164423*wi**2+.016666*wi**3
       aai = omai*(((R**2)*(tci**2))/pci)*((1+(fwi*(1-(tri**.5))))**2)
       n+1

#bi = ombi*((R*tci)/pci)
print(aai)

Instead of while use a for loop with range() . Something like this should work:

for n in range(7)  :
   if wi[n] <= .49 :
      fwi = .374640+1.54226*wi[n]-.26992*wi[n]**2           
   else :
      fwi = .379642+1.48503*wi[n]-.164423*wi[n]**2+.016666*wi[n]**3
   aai[n] = omai[n]*(((R**2)*(tci[n]**2))/pci[n])*((1+(fwi*(1-(tri[n]**.5))))**2)

TL;DR: See "Actual Solution" below.
But first, addressing each issue in the code:

  1. If wi is a series of numbers, you don't need to hardcode that it needs to run the loop 7 times. You could just iterate over the values of wi .

  2. Assigning directly to aai inside the loop overwrites the existing aai and it's not longer a np.zeroes() array. You could initialise it as a regular empty Python list and append to it. And at the end of the loop, convert it to an array.

  3. The aai = omai*... assignment is currently indented to be only inside the else block but based on your question, it should probably occur in either case of the value being less than or equal to 0.49 or not. And should be an append() .

So your loop would look like:

aai = []  # empty Python list
for val in wi:
    if val <= .49:
        fwi = .374640+1.54226*val-.26992*val**2
    else:
        fwi = .379642+1.48503*val-.164423*val**2+.016666*val**3
    aai.append(omai*(((R**2)*(tci**2))/pci)*((1+(fwi*(1-(tri**.5))))**2))

aai = np.array(aai)  # convert it to a numpy array if needed as a numpy array

Also, that if-else block could be simplified to using Python's ternary operator aka "Conditional expressions" :

aai = []
for value in wi:
    fwi = .374640+1.54226*val-.26992*val**2 if val <= .49 else .379642+1.48503*val-.164423*val**2+.016666*val**3
    aai.append(omai*(((R**2)*(tci**2))/pci)*((1+(fwi*(1-(tri**.5))))**2))

aai = np.array(aai)

Actual solution:
But since you're working with numpy arrays, you could just set up an array of fwi values using np.where() which assigns values (either formula) based on the condition's True/False-ness for each value in wi . And then calculate aai in one step as an array operation. No for-loop, hardcoded length, or if-else needed.

# newlines added for readability
fwi = np.where(wi < 0.49,
               .374640+1.54226*wi-.26992*wi**2,
               .379642+1.48503*wi-.164423*wi**2+.016666*wi**3)
aai = omai*(((R**2)*(tci**2))/pci)*((1+(fwi*(1-(tri**.5))))**2)  # becomes an array operation

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