Python Pandas - 创建一个 PeriodIndex 并获取一周中的天数

要创建 PeriodIndex,请使用方法。使用PeriodIndex.dayofweek属性获取星期pandas.PeriodIndex()

首先,导入所需的库 -

import pandas as pd

创建一个 PeriodIndex 对象。PeriodIndex 是一个不可变的 ndarray,其中包含指示定期时间段的序数值。我们使用“freq”参数设置了频率 -

periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

显示 PeriodIndex 对象 -

print("PeriodIndex...\n", periodIndex)

显示来自 PeriodIndex 对象的星期几。星期几显示为星期一 = 0,星期二 = 1 ...星期日 = 6 -

print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

示例

以下是代码 -

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency...\n", periodIndex.freq)

# Display day from the PeriodIndex object
print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

# Display day of the week from the PeriodIndex object
# Days of week are displayed as Monday=0, Tuesday=1 ... Sunday=6
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)
输出结果

这将产生以下代码 -

PeriodIndex...
PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'],
dtype='period[D]')

PeriodIndex frequency...
<Day>

The number of days from the PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')

Days of the week from the PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')

猜你喜欢