# 通过检查熊猫中指定的8种条件从输入字典生成df

``````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。

``````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):

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):

7. if (start_date == 0) and (end_date == 0) and (n_days != 0):

8. if (start_date == 0) and (end_date == 0) and (n_days == 0):
``````

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

``````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')
``````

``````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
``````

0 条评论