python - 如何使用 pandas 指定给定日期的周数?

标签 python pandas dataframe

我有一个使用的数据框

year_start = '2020-03-29'

year_end = '2021-04-10'

week_end_sat = pd.DataFrame(pd.date_range(year_start, year_end, freq=f'W-SAT'), columns=['a'])

由于我正在尝试制作始终在星期六结束的 4-4-5 日历,因此如何制作另一列指定周数,将 2020-03-29 作为日历的第一天?

我想要的最终 df 是,

     a     |  count
2020-04-04 |    1
2020-04-11 |    2
.
.
.
2021-04-03 |    53   #since 2020 is a leap year there are 53 weeks otherwise it will be 52 weeks
2021-04-10 |    1
2021-04-17 |    2
.
2022-03-02 |    52
2022-04-09 |    1

最佳答案

我认为您可以创建一个从给定 year_start 的第一天开始的基准日期范围。

first_day_of_year = week_end_sat.iloc[0, 0].replace(day=1, month=1)
baseline = pd.Series(pd.date_range(first_day_of_year, periods=len(week_end_sat), freq=f'W-SAT'))

一年中的基准周就是您想要的。

week_end_sat['count'] = baseline['a'].dt.isocalendar().week
# print(week_end_sat)

            a  count
0  2020-04-04     1
1  2020-04-11     2
2  2020-04-18     3
3  2020-04-25     4
4  2020-05-02     5
5  2020-05-09     6
6  2020-05-16     7
7  2020-05-23     8
8  2020-05-30     9
9  2020-06-06    10
10 2020-06-13    11
11 2020-06-20    12
12 2020-06-27    13
13 2020-07-04    14
14 2020-07-11    15
15 2020-07-18    16
16 2020-07-25    17
17 2020-08-01    18
18 2020-08-08    19
19 2020-08-15    20
20 2020-08-22    21
21 2020-08-29    22
...
43 2021-01-30    44
44 2021-02-06    45
45 2021-02-13    46
46 2021-02-20    47
47 2021-02-27    48
48 2021-03-06    49
49 2021-03-13    50
50 2021-03-20    51
51 2021-03-27    52
52 2021-04-03    53
53 2021-04-10     1

关于python - 如何使用 pandas 指定给定日期的周数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67055127/

相关文章:

python - 计算从 Pandas value_counts() 中提取的值

python - Pandas 读取嵌套的 json

python - Spyder、变量浏览器、xpt

python - 使用 Index 与 MultiIndex 的 Pandas Dataframe 日期时间切片

python - Pandas 中一列的值作为列,同时保持最后更新

python - matplotlib.pyplot 和 matplotlib.figure 有什么区别?

python - 用Python测试嵌入式系统的测试框架

python - 当一列是日期时间而另一列是对象时,如何连接/合并 Pandas 中的两列?

python - 由于 "ImportError: No module named six"无法安装软件包

python - 如何从列表类别中对 pandas 数据框进行排序?