我具有以下功能,该功能包含会员的登录日期和合同期限,并返回修改后的数据框,其中包含每个会员的到期日期。该函数按预期工作,但我想知道是否有更简洁的方法来编写嵌套函数month_to_num(ind)
。我知道python没有实现cases
,但有没有办法重写所有if/elif/else
语句?
def renewal_date(df):
def month_to_num(ind):
if (df.loc[ind, "Contract Type"] == "1 Month"):
return 1
elif (df.loc[ind, "Contract Type"] == "3 Months Prom" or
df.loc[ind, "Contract Type"] == "3 Month"):
return 3
elif (df.loc[ind, "Contract Type"] == "4 Month Promo"):
return 4
elif (df.loc[ind, "Contract Type"] == "6 Months"):
return 6
else:
return 12
for z in range(0, len(df)):
exp_date = (df.loc[z, "Date-Joined"] +
relativedelta(months=+month_to_num(z)))
df.set_value(z,"Date-Renewal", exp_date)
return df
答案 0 :(得分:2)
这更适合Code Review Stack Exchange,但为了保留功能,您通常会使用字典:
MONTH_NUMS = {
'1 Month': 1,
'3 Months Prom': 3,
'3 Month': 3,
'4 Month Promo': 4,
'6 Months': 6,
}
def month_to_num(ind):
return MONTH_NUMS.get(df.loc[ind, 'Contract Type'], 12)
那就是说,这里有一些代码味道我们如何用这种方式将字符串映射到数字。
答案 1 :(得分:1)
您可以使用与dict.get()
方法协调的字典,如果字典中不存在该键,则会返回默认值。
def renewal_date(df):
def month_to_num(ind):
contract_types = {'1 Month': 1, '3 Months Prom': 3, '4 Month Promo': 4, '6 Months': 6}
return contract_types.get(df.loc[ind, "Contract Type"], 12)
for z in range(0, len(df)):
exp_date = (df.loc[z, "Date-Joined"] +
relativedelta(months=+month_to_num(z)))
df.set_value(z, "Date-Renewal", exp_date)
return df