我有一个数据框:
df =
|date months_left amount
0|06/09/2019 34 150000
1|25/12/2019 23 70000
2|13/01/2020 7 85000
...
我想定义一个带有日期参数并在数据框中的每一行中运行的函数。它将在数据框中的日期上加上months_left,如果结果日期超过函数中提到的参数日期,则在新列中该值应为0,如果它在参数date下,则该值应相同。因此,理想情况下,如果函数中的参数为2021年12月31日,则它将看起来像这样。
|date months_left amount new_amount
0|06/09/2019 34 150000 0
1|25/12/2019 23 70000 70000
2|13/01/2020 7 85000 85000
对于第一行,添加到months_left的日期超过31/12/2021,结果值为0。其他行没有超过31/12/2021,因此其金额不受影响
首先确保您的date
栏是日期时间
df["date"] = pd.to_datetime(df["date"]) # note it is better to do this when you read the data
然后,您可以使用这种方法来确定您是否在结束日期之前
end_date = datetime.date(2021, 12, 31) # note you need to import datetime
past_end_date = (df.date.values.astype("datetime64[M]") + df.months_left.values.astype("timedelta64[M]")) > end_date
# Note a pandas TimedeltaIndex might be an alternative to this numpy approach https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.TimedeltaIndex.html
# i.e. past_end_date = (df["date"] + pd.TimedeltaIndex(df["months_left"], unit="M")) > end_date
# the answers will be a bit different on edge cases
现在做一些索引
df["new_amount"] = df["amount"]
df.loc[past_end_date, "new_amount"] = 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句