[英]Apply a specific function to a column of a data frame in pandas
我有一个如下所示的数据框
Date in_days
2020-02-01 1
2020-02-06 6
2020-02-09 9
2020-02-03 3
2020-02-11 11
2020-02-21 21
2020-02-13 13
2020-02-29 29
2020-02-26 26
我想创建一个 function 它将从 in_days 创建一个名为 t_factor 的新列,如下所示。
t = in_days
if 0 < in_days <= 4:
t_factor = (3*in_days) + 2
else if 4 < in_days <= 12:
t_factor = 14
else:
t_factor = (in_days)**2 + (2*in_days) + 2
预期 output:
Date in_days t_factor
2020-02-01 1 5
2020-02-06 6 14
2020-02-09 9 14
2020-02-03 3 11
2020-02-11 11 14
2020-02-20 20 442
2020-02-13 10 12
2020-02-29 25 677
2020-02-26 2 8
您的代码中的t
与in_days
相同。 在这种情况下,您可以这样做:
df['t_factor'] = np.select( (df['in_days'].gt(0) & df['in_days'].le(4),
df['in_days'].gt(4) & df['in_days'].le(12)),
(df['in_days']*3+2, 14), # is this 12 or 14?
df['in_days']**2 + df['in_days']*2 + 2)
Output:
Date in_days t_factor
0 2020-02-01 1 5
1 2020-02-06 6 14
2 2020-02-09 9 14
3 2020-02-03 3 11
4 2020-02-11 11 14
5 2020-02-20 20 442
6 2020-02-13 10 14
7 2020-02-29 25 677
8 2020-02-26 2 8
您可以使用map
function 执行此操作,如下所示:
df['A'].map(multiply)
其中multiply
是要应用的 function 名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.