我有一本字典,如下所示。
d1 = { 'start_date' : '2020-10-01T20:00:00.000Z',
'end_date' : '2020-10-05T20:00:00.000Z',
'n_days' : 6,
'type' : 'linear',
"coef": [0.1,0.1,0.1,0.1,0.1,0.1]
}
d1:是用户输入的内容,用户可能输入了错误的开始日期,结束日期和n_days。
我们必须更换 end_date = start_date + n_days
可能存在start_date
,end_date
和n_days
不可用的情况。由指定的非可用性start_date = 0, end_date = 0, n_days = 0
。
然后我们将有8个条件
1. if (start_date != 0) and (end_date != 0) and (n_days != 0):
end_date = start_date + n_days
2. if (start_date != 0) and (end_date != 0) and (n_days == 0):
pass
3. if (start_date != 0) and (end_date == 0) and (n_days != 0):
end_date = start_date + n_days
4. if (start_date != 0) and (end_date == 0) and (n_days == 0):
print("Please enter required inputs")
5. if (start_date == 0) and (end_date != 0) and (n_days != 0):
start_date = end_date - n_days
6. if (start_date == 0) and (end_date != 0) and (n_days == 0):
print("Please enter required inputs")
7. if (start_date == 0) and (end_date == 0) and (n_days != 0):
print("Please enter required inputs")
8. if (start_date == 0) and (end_date == 0) and (n_days == 0):
print("Please enter required inputs")
我想通过检查d1并入上述所有条件。之后,我想根据上面处理的d1在df以下进行准备。
从上面,字典作为函数的输入,我想在df以下生成作为输出。
预期产量:
df:
Date Day function_type function_value
2020-10-01 1 linear (0.1*1)+0.1 = 0.2
2020-10-02 2 linear (0.1*2)+0.1 = 0.3
2020-10-03 3 linear (0.1*3)+0.1 = 0.4
2020-10-04 4 linear (0.1*4)+0.1 = 0.5
2020-10-05 5 linear (0.1*5)+0.1 = 0.6
注意:
类型可以是线性,常数,多项式和指数。
a0, a1, a2, a3, a4, a5 = d1['coef']
If constant, funtion_value = a0
If exponential funtion_value = e**(a0+a1T)
if polynomial
funtion_value = a0+a1T+a2(T**2)+a3(T**3)+a4(T**4)+a5(T**5)
T = value of Day column
@Shubham Sharma和@Let的尝试很好地回答了类似的问题,请尝试根据特定条件和输入字典生成数据框-熊猫
非常感谢@Shubham Sharma和@让我们尝试
延长我previous answer
的question
,我们可以创建自定义validation
机能的研究,是以输入参数由用户提供的字典,并返回一个两对tuple
具有有效start_date
和end_date
以其他方式筹集的ValueError
:
def validate(d):
n_days, start, end = d['n_days'], d['start_date'], d['end_date']
if start == 0:
if end != 0 and n_days != 0:
end = pd.to_datetime(end)
start = end - pd.Timedelta(days=n_days)
else:
raise ValueError('Invalid user input')
else:
start = pd.to_datetime(start)
if end != 0 and n_days != 0:
end = pd.to_datetime(end)
elif end == 0 and n_days == 0:
raise ValueError('Invalid user input')
else:
end = start + pd.Timedelta(days=n_days)
return start.tz_localize(None).floor('D'),\
end.tz_localize(None).floor('D')
然后getDF
从中修改函数,previous answer
并包含try-except
要捕获的语句ValueError
:
def getDF(d):
try:
start, end = validate(d)
date = pd.date_range(start, end, freq='D')
days = (date - date[0]).days + 1
return pd.DataFrame({'Date': date, 'Day': days, 'function_type': d['type'],
'function_value': funcValue(d, days)})
except ValueError as err:
print(err)
结果:
print(getDF(d1))
Date Day function_type function_value
0 2020-10-01 1 linear 0.2
1 2020-10-02 2 linear 0.3
2 2020-10-03 3 linear 0.4
3 2020-10-04 4 linear 0.5
4 2020-10-05 5 linear 0.6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句