[英]More Succinct Elif Statement
Is there a way to more efficiently code this? 有没有一种方法可以更有效地对此进行编码? I tried np.where but there are so many conditions and they're so complex I couldn't get it to work properly.
我尝试了np.where,但是条件太多了,而且它们是如此复杂,以至于无法正常工作。 I know there has to be a faster way then a massive elif statement, but It's the only way I could dump all of my conditions in there.
我知道必须有一条比大规模的elif语句更快的方法,但这是我可以在其中转储所有条件的唯一方法。 I'm running through about 1 million lines of excel so if there are other faster options I'd like to hear them!
我正在运行大约一百万行excel,因此,如果还有其他更快的选择,我想听听他们的意见!
Here is the code: 这是代码:
def pol_cost(x):
if ( 9500000> x.CRV >= 50 ):
if (x.MDI > MDI_var):
if (x.CI < 40 ):
return x.CRV
elif (60 <= x.CI <80):
return x.CRV*((100-x.CI)/(100-var_var))**x.Cost_Escalation_N
else:
return 0
else:
return 0
df1['Policy_Cost_Y1'] = df1.apply(pol_cost, axis = 1)
@chepner's simplificiation of your conditional statements allows you to then vectorize the entire operation to @chepner对条件语句的简化使您可以将整个操作向量化为
a = x.CI < 40
b = numpy.logical_and(
60 <= x.CI,
x.CI < 80,
)
c = numpy.logical_or(
numpy.logical_and(
9500000 > x.CRV,
x.CRV >= 50
),
x.MDI <= MDI_var,
)
tmp = numpy.zeros_like(x.CRV)
tmp[a] = x.CRV[a]
tmp[b] = x.CRV[b] * ((100-x.CI[b])/(100 - var_var))**x.Cost_Escalation_N[b],
tmp[c] = 0
df1['Policy_Cost_Y1'] = tmp
A useful idiom is to handle the clause the returns immediately; 一个有用的习惯用法是立即处理返回的子句。 then you don't need an
else
or elif
. 那么您不需要
else
或elif
。
def pos_cost(x):
if not (9500000 > x.CRV >= 50):
return 0
if x.MDI <= MDI_var:
return 0
if x.CI < 40:
return x.CRV
elif 60 < x.CI < 80:
return x.CRV * ((100-x.CI)/(100 - var_var))**x.Cost_Escalation_N
df1['Policy_Cost_Y1'] = df1.apply(pol_cost, axis=1)
Note that since the first two if
statements have the same result, you can combine them into a single statement: 请注意,由于前两个
if
语句具有相同的结果,因此可以将它们组合为一个语句:
if not (9500000 > x.CRV >= 50) or (x.MDI <= MDI_var):
return 0
or after a little manipulation: 或稍加操作后:
if 9500000 <= x.CRV or x.CRV < 50 or x.MDI <= MDI_var:
You can combine the two first conditions with and
and test the inverse of that. 您可以将的第一个条件与
and
结合使用and
然后测试其反函数。 Then go with elif
statements. 然后使用
elif
语句。
if not (9500000 > x.CRV >= 50 and x.MDI > MDI_var):
return 0
elif x.CI < 40 :
return x.CRV
elif 60 <= x.CI <80:
return x.CRV*((100-x.CI)/(100-var_var))**x.Cost_Escalation_N
else:
df1['Policy_Cost_Y1'] = df1.apply(pol_cost, axis = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.