'Passing a list into a function that requires boolean [Python]
Im quite new to python so i apologize if this question is basic. say i have some simple function
def get_choiceCost(numChances,init_cost,ratio):
numChances[]
if np.equal(numChances,1):
c=init_cost
elif np.equal(numChances,2):
c=init_cost+init_cost/ratio
elif np.equal(numChances,3):
c=init_cost+init_cost/ratio+init_cost/np.power(ratio,2)
else:
c=0
return c
how do i pass an array for numChances which will have different truth values? For example,
Im hoping to add a column to a dataframe that takes whatever the value of numChances,init_cost and ratio is for that particular row and calculates the cost (i.e. get_choiceCost to those values). I tried
numChances=np.array([0,1,2])
init_cost=np.array([3,4,5])
rat=np.array([2,3])
products = np.array(np.meshgrid(numChances,init_cost,ratio)).T.reshape(-1, 3)
df = pd.DataFrame(products, columns= ["numChances","init_cost","ratio"]);
df["cost"]=df.apply(get_choiceCost(df["numChances"],df["init_cost"],df["rat"]),axis=0)
i get the error
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Solution 1:[1]
def get_choiceCost(row):
numChances = row.values[0]
init_cost = row.values[1]
ratio = row.values[2]
if np.equal(numChances, 1):
c=init_cost
elif np.equal(numChances, 2):
c=init_cost * 2 / ratio
elif np.equal(numChances, 3):
c=init_cost * 2 / ratio + init_cost / np.power(ratio, 2)
df["cost"] = df.apply(get_choiceCost, axis=0)
I think that should work, its not very elegant though, let me know if you have any issues.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ace |
