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

Python Pandas: Định dạng chuỗi biểu diễn PeriodIndex object

Phương thức periodIndex.strftime() trong Pandas định dạng chuỗi biểu diễn của PeriodIndex object. Sử dụng các format specifier giống như datetime.strftime().

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:30:35', '2019-10-30 04:15:45', 
     '2020-07-15 02:55:15', '2022-06-25 09:40:55'], 
    freq="Y"
)

3. Hiển thị PeriodIndex

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

4. Định dạng chuỗi

print("\nString representation (format with different directives)...\n", 
      periodIndex.strftime('%b. %d, %Y was a %A'))

Ví dụ hoàn chỉnh

import pandas as pd

periodIndex = pd.PeriodIndex(
    ['2021-09-25 07:30:35', '2019-10-30 04:15:45', 
     '2020-07-15 02:55:15', '2022-06-25 09:40:55'], 
    freq="Y"
)
print("PeriodIndex...\n", periodIndex)
print("\nPeriodIndex frequency object...\n", periodIndex.freq)
print("\nPeriodIndex frequency as string...\n", periodIndex.freqstr)
print("\nString representation (format with different directives)...\n", 
      periodIndex.strftime('%b. %d, %Y was a %A'))

Kết quả đầu ra

PeriodIndex...
PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]')
PeriodIndex frequency object...
<YearEnd: month=12>
PeriodIndex frequency object as a string...
A-DEC
String representation (format with different directives)...
Index(['Dec. 31, 2021 was a Friday', 'Dec. 31, 2019 was a Tuesday', 
       'Dec. 31, 2020 was a Thursday', 'Dec. 31, 2022 was a Saturday'], dtype='object')

Giải thích:

  • PeriodIndex tần suất Y (YearEnd) đại diện cho cuối năm (31/12)
  • Format '%b. %d, %Y was a %A' tạo chuỗi như "Dec. 31, 2021 was a Friday"
  • Kết quả trả về Index với dtype object (chuỗi)

Format specifier phổ biến

Directive Ý nghĩa Ví dụ
%Y Năm 4 chữ số 2021
%y Năm 2 chữ số 21
%m Tháng (01-12) 09
%b Tên tháng viết tắt Sep
%B Tên tháng đầy đủ September
%d Ngày (01-31) 25
%A Tên thứ đầy đủ Monday
%a Tên thứ viết tắt Mon
%H Giờ (00-23) 07
%M Phút (00-59) 30
%S Giây (00-59) 35