📜  Python| Pandas Period.dayofweek(1)

📅  最后修改于: 2023-12-03 15:34:16.163000             🧑  作者: Mango

Python | Pandas Period.dayofweek

在 Pandas 中,Period 对象表示时间段,可以表示带有特定频率(如日、月、季度等)的时期。Pandas 中的 Period 类有一个 dayofweek 属性,用于获取一周中的第几天,返回一个整数,其中周一是 0,周二是 1,以此类推。

语法
period.dayofweek
参数

返回值

返回一个整数,表示一周的第几天,其中周一是 0,周二是 1,以此类推。

示例
import pandas as pd

# 创建一个表示 2021 年 5 月 1 日的 Period 对象
date = pd.Period('2021-05-01', freq='D')

# 获取这一天是周几
weekday = date.dayofweek
print(weekday)  # 输出:5

上面的例子中,通过创建一个表示 2021 年 5 月 1 日的 Period 对象,获取这一天是周几,并将结果存储在变量 weekday 中。由于 2021 年 5 月 1 日是星期六,因此 weekday 的值为 5。

import pandas as pd

# 创建表示 2021 年 5 月中旬每天的 Period 对象
dates = pd.period_range('2021-05-15', '2021-05-31')

# 遍历每个时期并获取周几
for date in dates:
    weekday = date.dayofweek
    print(date, weekday)

上面的例子中,创建了一个表示 2021 年 5 月中旬到月底期间每天的 Period 对象,并遍历每个时期,获取每天是星期几,并将结果打印出来。输出结果如下:

2021-05-15 5
2021-05-16 6
2021-05-17 0
2021-05-18 1
2021-05-19 2
2021-05-20 3
2021-05-21 4
2021-05-22 5
2021-05-23 6
2021-05-24 0
2021-05-25 1
2021-05-26 2
2021-05-27 3
2021-05-28 4
2021-05-29 5
2021-05-30 6
2021-05-31 0

在上面的例子中,使用了 period_range 函数创建了一个时间段范围,并遍历了每个时期,获取每天是星期几,并将结果打印出来。可以看到,结果正确地显示出了每天是星期几的信息。