我有一个包含两列、日期和类别的 DataFrame。我想根据规则创建一个新的日期列:如果类别是B那么值应该是最接近日期的工作日(仅来自过去或当天本身),否则它是日期列本身的值。
我将工作日定义为不在周末的任何一天,也不出现在holidays下面最小示例中定义的列表中。
请考虑以下 DataFrame df:
import datetime as dt
import pandas as pd
from IPython.display import display
holidays = [dt.datetime(2018, 10, 11)]
df = pd.DataFrame({"day": ["2018-10-10", "2018-10-11", "2018-10-12",
"2018-10-13", "2018-10-14", "2018-10-15"
],
"category":["A", "B", "C", "B", "C", "A"]
}
)
df["day"] = pd.to_datetime(df.day, format="%Y-%m-%d")
display(df)
day category
0 2018-10-10 A
1 2018-10-11 B
2 2018-10-12 C
3 2018-10-13 B
4 2018-10-14 C
5 2018-10-15 A
如何获得第三列,其值为下面列出的值?
2018-10-10
2018-10-10
2018-10-12
2018-10-12
2018-10-14
2018-10-15
我创建了一个函数,可以在处理列表时查找最后一个工作日,如果有帮助的话。
# creates a list whose elements are all days in the years 2017, 2018 and 2019
days = [dt.datetime(2017, 1 , 1) + dt.timedelta(k) for k in range(365*3)]
def lastt_bus_day(date):
return max(
[d for d in days if d.weekday() not in [5, 6]
and d not in holidays
and d <= date
]
)
for d in df.day:
print(last_bus_day(d))
#prints
2018-10-10 00:00:00
2018-10-10 00:00:00
2018-10-12 00:00:00
2018-10-12 00:00:00
2018-10-12 00:00:00
2018-10-15 00:00:00
跃然一笑
相关分类