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

Python Pandas: Trả về tần suất dạng chuỗi từ PeriodIndex object

Thuộc tính PeriodIndex.freqstr trong Pandas trả về tần suất (frequency) của PeriodIndex object dưới dạng chuỗi (string).

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

1. Import thư viện

import pandas as pd

2. Tạo PeriodIndex

periodIndex = pd.PeriodIndex(
    ['2021-09-25 07:50:35', '2019-10-30 04:35:45', 
     '2021-07-15 02:25:15', '2022-06-25 07:20:55'], 
    freq="T"
)

3. Hiển thị PeriodIndex

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

4. Lấy tần suất dạng chuỗi

print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)

Ví dụ hoàn chỉnh

import pandas as pd

periodIndex = pd.PeriodIndex(
    ['2021-09-25 07:50:35', '2019-10-30 04:35:45', 
     '2021-07-15 02:25:15', '2022-06-25 07:20:55'], 
    freq="T"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency object as a string...\n", periodIndex.freqstr)

Kết quả đầu ra

PeriodIndex...
PeriodIndex(['2021-09-25 07:50', '2019-10-30 04:35', '2021-07-15 02:25', '2022-06-25 07:20'], dtype='period[T]')
PeriodIndex frequency object...
<Minute>
PeriodIndex frequency object as a string...
T

Giải thích:

  • freq trả về object <Minute>
  • freqstr trả về chuỗi 'T' (mã tần suất chuẩn)
  • T = Minute (phút), cũng có thể viết 'min'

Các mã freqstr phổ biến

freqstr Tần suất
A / Y Năm (YearEnd)
Q Quý (QuarterEnd)
M Tháng (MonthEnd)
W Tuần (Week)
D Ngày (Day)
B Ngày làm việc (BusinessDay)
H Giờ (Hour)
T / min Phút (Minute)
S Giây (Second)
L / ms Millisecond
U / us Microsecond
N Nanosecond