在下面的数据框中,'end_of_week'列尚不存在。我试图这样做,如果'date'小于或等于那周的星期四,'end_of_week'是星期四。我该怎么做呢?
我正在尝试做什么:
df['end_of_week'] = Thursday of same week if df['date'] <= Thursday
示例:
0 date end_of_week
1 2015-08-31 2015-09-03 #if <= Thursday of that week
2 2015-09-01 2015-09-03
3 2015-09-07 2015-09-10
4 2015-09-09 2015-09-10
5 2015-09-16 2015-09-17
6 2015-09-17 2015-09-17
感谢。
答案 0 :(得分:1)
怎么样:
df['end_of_week'] = df['date'].map(lambda x: next_weekday(x, 3) if x.weekday() < 3 else x)
其中,来自@ phihag在Find the date for the first Monday after a given a date的答案:
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0:
days_ahead += 7
return d + datetime.timedelta(days_ahead)
做一个测试:
import pandas as pd
import datetime
xl3 = pd.ExcelFile('test2.xlsx')
df3 = xl3.parse("Sheet1")
df3
Out[71]:
x y date
0 1 fum 2015-06-01
1 2 fo 2015-06-02
2 3 fi 2015-06-03
3 4 fee 2015-06-04
4 5 dumbledum 2015-06-05
5 6 dumbledee 2015-06-06
df3['end_of_week'] = df3['date'].map(lambda x: next_weekday(x, 3) if x.weekday() < 3 else x)
df3
x y date end_of_week
0 1 fum 2015-06-01 2015-06-04
1 2 fo 2015-06-02 2015-06-04
2 3 fi 2015-06-03 2015-06-04
3 4 fee 2015-06-04 2015-06-04
4 5 dumbledum 2015-06-05 2015-06-05
5 6 dumbledee 2015-06-06 2015-06-06
答案 1 :(得分:1)
您可以使用arrow查找最近的星期四。艾尔星期一是星期一的第二天。
import arrow
THURSDAY = 3
arw = arrow.get("2015-08-31")
arw = arw.replace(days= +(THURSDAY - arw.weekday())).format('YYYY-MM-DD')
#=> arw = '2015-09-03'
直接解决您的问题:
import arrow
THURSDAY = 3
dates = [
"2015-08-31",
"2015-09-01",
"2015-09-07",
"2015-09-09",
"2015-09-16",
"2015-09-17",
]
end_of_week_dates = []
for date in dates:
arw = arrow.get(date)
if arw.weekday() <= THURSDAY:
end_of_week = arw.replace(days= +(THURSDAY - arw.weekday())).format('YYYY-MM-DD')
end_of_week_dates.append(end_of_week)
else:
# handle the case where the date is after the Thursday of that week
# end_of_week_dates = [
# '2015-09-03',
# '2015-09-03',
# '2015-09-10',
# '2015-09-10',
# '2015-09-17',
# '2015-09-17'
# ]