Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas: Tạo PeriodIndex và lấy số ngày trong tháng

Thuộc tính PeriodIndex.daysinmonth trong Pandas trả về số ngày của tháng chứa từng period trong PeriodIndex object.

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo PeriodIndex tần suất ngày

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

3. Hiển thị PeriodIndex

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

4. Lấy số ngày trong tháng

print("\nSố ngày của tháng từ PeriodIndex...\n", periodIndex.daysinmonth)

Ví dụ hoàn chỉnh

import pandas as pd

periodIndex = pd.PeriodIndex(
    ['2018-07-25', '2019-10-30', '2020-11-20', 
     '2021-09-15', '2022-03-12', '2023-06-18'], 
    freq="D"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency...\n", periodIndex.freq)
print("\nSố tháng...\n", periodIndex.month)
print("\nSố ngày của tháng từ PeriodIndex...\n", periodIndex.daysinmonth)

Kết quả đầu ra

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>
Số tháng...
Int64Index([7, 10, 11, 9, 3, 6], dtype='int64')
Số ngày của tháng từ PeriodIndex...
Int64Index([31, 31, 30, 30, 31, 30], dtype='int64')

Giải thích:

  • Tháng 7 (2018): 31 ngày
  • Tháng 10 (2019): 31 ngày
  • Tháng 11 (2020): 30 ngày
  • Tháng 9 (2021): 30 ngày
  • Tháng 3 (2022): 31 ngày
  • Tháng 6 (2023): 30 ngày

Lưu ý: Năm 2020 là năm nhuận nhưng tháng 11 vẫn 30 ngày. Thuộc tính này tự động xử lý năm nhuận cho tháng 2 (28/29 ngày).