Home > Blockchain >  Create a Function with 'while' loop in python and use the function to generate a new colum
Create a Function with 'while' loop in python and use the function to generate a new colum

Time:04-20

I tried to create a new function with "while" in Python.

def pmv_calculator(ta, tr, vel, rh, met, clo, wme):
pa = rh * 10 * np.exp(16.6536 - 4030.183 / (ta   235))
icl = 0.155 * clo
m = met * 58.15
w = wme * 58.15
mw = m - w
if icl <= 0.078:
    fcl = 1   (1.29 * icl)
else:
    fcl = 1.05   (0.645 * icl)

hcf = 12.1 * np.sqrt(vel)
taa = ta   273
tra = tr   273
tcla = taa   (35.5 - ta) / (3.5 * icl   0.1)

p1 = icl * fcl
p2 = p1 * 3.96
p3 = p1 * 100
p4 = p1 * taa
p5 = 308.7 - 0.028 * mw   p2 * np.power(tra / 100, 4)
xn = tcla / 100
xf = tcla / 50
eps = 0.00015
hc = 0

n = 0
while abs(xn - xf) > eps:
    xf = (xf   xn) / 2
    hcn = 2.38 * np.power(abs(100.0 * xf - taa), 0.25)
    if hcf > hcn:
        hc = hcf
    else:
        hc = hcn
    xn = (p5   p4 * hc - p2 * np.power(xf, 4)) / (100   p3 * hc)
    n  = 1
    if n > 150:
        print('Max iteration exceeded')
        break

tcl = 100 * xn - 273
h11 = 3.05 * 0.001 * (5733 - (6.99 * mw) - pa)
if mw > 58.15:
    h12 = 0.42 * (mw - 58.15)
else:
    h12 = 0
h13 = 1.7 * 0.00001 * m * (5867 - pa)
h14 = 0.0014 * m * (34 - ta)
h15 = 3.96 * fcl * (np.power(xn, 4) - np.power(tra / 100, 4))
h16 = fcl * hc * (tcl - ta)
ts = 0.303 * np.exp(-0.036 * m)   0.028
pmv = ts * (mw - h11 - h12 - h13 - h14 - h15 - h16)

return pmv

Then use this function to generate another column in my data frame.

df['PMV'] = pmv_calculator(df['temp'], df['temp'], 0.1, 22, 1.1, 1, 0)

But it gives me the following error:

File "C:/P.py", line 119, in df['PMV'] = pmv_calculator(df['temp'], df['temp'], Air_Speed, 22, Metabolic_Rate, Clothing, 0) File "C:/P.py", line 83, in pmv_calculator while abs(xn - xf) > eps: File "C:\PA\venv\lib\site-packages\pandas\core\generic.py", line 1538, in nonzero f"The truth value of a {type(self).name} is ambiguous. " ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

The Function works fine when I simply put numbers instead of a data frame column. The error just appears when I try to make a new column. I wrote the "while" loop with "|" but it did not work. I do not have any idea how I can fix it.

CodePudding user response:

The error is because of this line

while abs(xn - xf) > eps:

This type of comparison works best for a single value. But in a data frame you have multiple values, so this will not work. In your case the best solution is to use df.apply(). This will apply the pmv_calculator function to each row individually.

df['PMV'] = df.apply( lambda x : pmv_calculator(x['temp'], x['temp'], 0.1, 22, 1.1, 1, 0), axis=1)
  • Related