我想把每个月的哪一周作为一列。比如2022-10-04将是10月的第一周。我该怎么做呢?
<表类>
日期
tbody><<tr>2022-10-04 2022-10-04 2022-10-06 2022-10-12 2022-10-19 2022-10-25 2022-10-31 2022-11-02 2022-11-03 表类>
我写了一些代码,但是看起来你的样本数据和我的有不同的结果。
import pandas as pd
from math import ceil
import calendar
#from this post https://stackoverflow.com/questions/3806473/week-number-of-the-month
def week_of_month(dt):
first_day = dt.replace(day=1)
dom = dt.day
adjusted_dom = dom + first_day.weekday()
week_num = int(ceil(adjusted_dom/7.0))
month_name = calendar.month_abbr[dt.month]
return f'Week{week_num}_{month_name}'
#Creating a sample DataFrame
df = pd.DataFrame({'date': ['2022-10-04', '2022-10-04', '2022-10-06', '2022-10-19', '2022-11-02']})
df['date'] = pd.to_datetime(df['date'])
df['week'] = df['date'].apply(week_of_month)
print(df)
结果:
<表类> 日期一周 tbody><<tr>2022-10-04 Week2_Oct 2022-10-04 Week2_Oct 2022-10-06 Week2_Oct 2022-10-19 Week4_Oct 2022-11-02 Week1_Nov 表类>