【发布时间】:2020-11-25 08:49:24
【问题描述】:
将一周的开始自定义为星期四,将一周的结束自定义为星期三以提取周数
我尝试过使用
df['Date'].dt.to_period('THU-F')
但是 df['Date'].dt.to_period('W-THU') 工作正常时它不起作用
【问题讨论】:
标签: python pandas numpy dataframe datetime
将一周的开始自定义为星期四,将一周的结束自定义为星期三以提取周数
我尝试过使用
df['Date'].dt.to_period('THU-F')
但是 df['Date'].dt.to_period('W-THU') 工作正常时它不起作用
【问题讨论】:
标签: python pandas numpy dataframe datetime
这似乎是一个直截了当的问题,但它有点棘手。要获得周数,从不同的一天开始一周,您首先必须获得该年所有可能的周。然后您必须进行累积计数才能获得周数。最后,您可以将周数与您的数据结合起来。这应该可以解决问题:
import random
import pandas
import datetime
def create_week_numbers(since: datetime.datetime = datetime.datetime(year=2019, month=1, day=1), until: datetime.datetime = datetime.datetime.now()) -> pandas.DataFrame:
""" Create a dataframe that contains "year", "week" (start-end dates), and "week_number" for all
possible dates between "since" and "until".
Args:
since (datetime.datetime, optional): The start date. Defaults to datetime.datetime(year=2019, month=1, day=1).
until (datetime.datetime, optional): The end date. Defaults to datetime.datetime.now().
Returns:
pandas.DataFrame: A dataframe with all possible weeks and week numbers
"""
# Generate every possible date since a start date until now
dates = [since]
while dates[-1] < until:
dates.append(dates[-1] + datetime.timedelta(days=1))
# Convert all the dates into a dataframe
all_dates = pandas.DataFrame(dates, columns=["date"])
# Add a column for the year, and add a column for the week (using the to_period method)
all_dates["year"] = all_dates["date"].dt.year
all_dates["week"] = all_dates["date"].dt.to_period("W-WED") # https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#anchored-offsets
# Ignore the individual days and keep only unique weeks per year
weeks_per_year = all_dates[["week", "year"]].drop_duplicates()
# Add the week number by incrementally counting the weeks by year
weeks_per_year["week_number"] = weeks_per_year.groupby(["year"]).cumcount()
# Return the year, the span of th week, and the week number in the year
return weeks_per_year[["year", "week", "week_number"]]
# Create a list of all week numbers
week_number_lookup = create_week_numbers()
# Generate some random test dataframes
df = pandas.DataFrame([{
"date": datetime.datetime.fromtimestamp(random.randint(1579947057, 1606297560)),
} for _ in range(10000)])
# Add the week to the dataframe
df["week"] = df["date"].dt.to_period("W-WED") # Week ends on Wednesday
# Merge with the lookup to find the week number
df.merge(on="week", right=week_number_lookup)
输出:
date week year week_number
0 2020-03-17 04:19:48 2020-03-12/2020-03-18 2020 11
1 2020-03-12 04:40:42 2020-03-12/2020-03-18 2020 11
2 2020-03-16 03:17:10 2020-03-12/2020-03-18 2020 11
3 2020-03-14 08:03:52 2020-03-12/2020-03-18 2020 11
4 2020-03-13 05:27:02 2020-03-12/2020-03-18 2020 11
... ... ... ... ...
9995 2020-05-12 00:55:55 2020-05-07/2020-05-13 2020 19
9996 2020-05-09 06:07:28 2020-05-07/2020-05-13 2020 19
9997 2020-05-08 10:01:15 2020-05-07/2020-05-13 2020 19
9998 2020-05-12 12:52:55 2020-05-07/2020-05-13 2020 19
9999 2020-05-07 15:46:41 2020-05-07/2020-05-13 2020 19
[10000 rows x 4 columns]
仅供参考,您原来的df['Date'].dt.to_period('THU-F') 不起作用的原因是它不是有效值。看看你在这里的选项:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#anchored-offsets
【讨论】: