如何对每个月的每个星期进行分组?——巨蟒熊猫

  • 本文关键字:熊猫 巨蟒 date
  • 更新时间 :
  • 英文 :


我想把每个月的哪一周作为一列。比如2022-10-04将是10月的第一周。我该怎么做呢?

<表类> 日期 tbody><<tr>2022-10-042022-10-042022-10-062022-10-122022-10-192022-10-252022-10-312022-11-022022-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-04Week2_Oct2022-10-04Week2_Oct2022-10-06Week2_Oct2022-10-19Week4_Oct2022-11-02Week1_Nov

相关内容

  • 没有找到相关文章

最新更新