Create A Specific Column By Looping Over The User Defined Dictionary In Pandas
I have a df as shown below. Date t_factor 2020-02-01 5 2020-02-03 23 2020-02-06 14 202
Solution 1:
I would propose that you store the data as a list of tuples. Like so,
params = [('2020-02-01', '2020-02-06', 3, 1, 0),
('2020-02-13', '2020-02-29', 2, 0, 1),
('2020-03-11', '2020-03-29', 4, 0, 0)]
Now all you need is to loop over params
and add the columns to your dataframe df
.
total = Nonefor i, param inenumerate(params):
s, e, a0, a1, a2 = param
df[f"t{i+1}"] = df.apply(lambda x: fun(x, s, e, a0, a1, a2), axis=1)
if i==0:
total = df[f"t{i+1}"].fillna(0)
else:
total += df[f"t{i+1}"].fillna(0)
df["t_function"] = total
This gives the desired output:
Datet_factort1t2t3t_function02020-02-01 54.0NaNNaN4.012020-02-03 236.0NaNNaN6.022020-02-06 149.0NaNNaN9.032020-02-09 23NaNNaNNaN0.042020-02-10 23NaNNaNNaN0.052020-02-11 23NaNNaNNaN0.062020-02-13 30NaN3.0NaN3.072020-02-20 29NaN66.0NaN66.082020-02-29 100NaN291.0NaN291.092020-03-01 38NaNNaNNaN0.0102020-03-10 38NaNNaNNaN0.0112020-03-11 38NaNNaN4.04.0122020-03-26 70NaNNaN4.04.0132020-03-29 70NaNNaN4.04.0
Post a Comment for "Create A Specific Column By Looping Over The User Defined Dictionary In Pandas"