根据特定条件和输入字典生成数据框- pandas
问题描述:
我有一个字典,如下所示.
I have a dictionary as shown below.
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]
}
从上面的字典作为函数的输入,我想在df以下生成作为输出.
From the above dictionary as input to the function, I would like to generate below df as output.
预期输出:
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
注意:
类型
可以是线性,常数,多项式和指数.
The type
can be linear, constant, polynomial and exponential.
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
答
定义函数 funcValue
,该函数从给定的输入字典 d计算函数值列
和天列 T
根据字典中的 type
类型:
Define a function funcValue
that computes the function value column from the given input dictionary d
and days column T
based on the type
in dictionary:
def funcValue(d, T):
a0, a1, a2, a3, a4, a5 = d['coef']
func = {
'constant': a0,
'linear': a0 + a1*T,
'polynomial': a0 + a1*T + a2*(T**2)+ a3 * (T**3) + a4*(T**4) + a5*(T**5),
'exponential': np.power(np.e, a0 + a1*T)
}
return func[d['type']]
然后定义一个函数 getDF
,该函数根据用户定义的词典 d
中提供的信息生成所需的数据框:
Then define a function getDF
that generates a required dataframe based on the information provided in the user defined dictionary d
:
def getDF(d):
date = pd.date_range(d['start_date'], d['end_date'], freq='D').tz_localize(None).floor('D')
days = (date - date[0]).days + 1
return pd.DataFrame({'Date': date, 'Day': days, 'function_type': d['type'],
'function_value': funcValue(d, days)})
结果:
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