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

Python Pandas: Trả về đối tượng tần suất từ PeriodIndex object

Thuộc tính PeriodIndex.freq trong Pandas trả về đối tượng tần suất (frequency object) của PeriodIndex, cung cấp thông tin chi tiết về tần suất.

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(
    ['2021-09-25', '2019-10-30', '2020-11-20', 
     '2021-07-15', '2022-06-12', '2023-07-10'], 
    freq="D"
)

3. Hiển thị PeriodIndex

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

4. Lấy đối tượng tần suất

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

Ví dụ hoàn chỉnh

import pandas as pd

periodIndex = pd.PeriodIndex(
    ['2021-09-25', '2019-10-30', '2020-11-20', 
     '2021-07-15', '2022-06-12', '2023-07-10'], 
    freq="D"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency...\n", periodIndex.freq)
print("\nSố tháng...\n", periodIndex.month)

Kết quả đầu ra

PeriodIndex...
PeriodIndex(['2021-09-25', '2019-10-30', '2020-11-20', '2021-07-15', '2022-06-12', '2023-07-10'], dtype='period[D]')
PeriodIndex frequency...
<Day>
Số tháng...
Int64Index([9, 10, 11, 7, 6, 7], dtype='int64')

Giải thích:

  • freq trả về object <Day> (lớp pandas.tseries.offsets.Day)
  • freqstr trả về chuỗi 'D'
  • Object freq cho phép truy cập các thuộc tính nâng cao như freq.n, freq.rule_code, v.v.

So sánh freq vs freqstr

Thuộc tính Kiểu trả về Ví dụ
freq Offset object <Day>, <MonthEnd>, <BusinessHour: BH=09:00-17:00>
freqstr String 'D', 'M', 'BH'