Ryan
Ryan

Reputation: 79

Python Truth value of a series is ambiguous error in Function

I 'm trying to build a function that uses several scalar values as inputs and one series or array also as an input.

The function applies calculations to each value in the series. It works fine so far. But now I'm adding a phase where it has to check the value of the series and if it's less than X it performs one calculation other it performs a different calculation.

However I keep getting a 'truth value series is ambiguous error and I can't seem to solve it.

What is a work around?

My code is below

import numpy as np
import pandas as pd
import math

tramp = 2
Qo = 750
Qi = 1500
b = 1.2
Dei = 0.8
Df = 0.08
Qf = 1
tmax = 30
tper = 'm'

t = pd.Series(range(1,11))

def QHyp_Mod(Qi, b, Dei, Df, Qf, tmax, tper, t):       
    tper = 12
    Qi = Qi * (365/12)
    Qf = Qf * (365/12)
        
    ai = (1 / b) * ((1 / (1 - Dei)) ** b - 1)
    aim = ai / tper
    
    ai_exp = -np.log(1 - Df)
    aim_exp = ai_exp / tper

    t_exp_sw = 118
    Qi_exp = Qi / ((1 + aim * t_exp_sw * b) ** (1 / b))
     
    Qcum = (Qi / (aim * (1 - b))) * (1 - (1 / ((1 + aim * t * b) ** ((1 - b) / b))))     
    
    t_exp = t - t_exp_sw 
    Qcum_Exp = (Qi_exp / aim_exp) * (1 - np.exp(-aim_exp * t_exp))
   
    if t < t_exp_sw:
        return Qcum
    else:
        return Qcum_exp

z = QHyp_Mod(Qi=Qi, b=b, Dei=Dei, Df=Df, Qf=Qf, tmax=tmax, tper=tper, t=t)

Upvotes: 0

Views: 65

Answers (1)

Dan
Dan

Reputation: 26

Replace the if - else statement:

if t < t_exp_sw:
    return Qcum
else:
    return Qcum_exp

with this:

Q.where(t < t_exp_sw, Q_exp)
return Q

The where method tests the conditional for each member of Q, if true keeps the original value, and if false replaces it with the corresponding element of Q_exp

Upvotes: 1

Related Questions