เพื่อจัดรูปแบบการแสดงสตริง (string representation) ของ PeriodIndex object ให้ใช้เมธอด periodIndex.strftime() ระบุตัวกำหนดรูปแบบ (format specifiers) เป็นอาร์กิวเมนต์
ขั้นตอนตัวอย่าง
import pandas as pd
# สร้าง PeriodIndex object (freq="Y" = รายปี)
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("\nความถี่ PeriodIndex...\n", periodIndex.freq)
print("\nความถี่ PeriodIndex เป็นสตริง...\n", periodIndex.freqstr)
# จัดรูปแบบสตริง
print("\nการแสดงสตริง (จัดรูปแบบด้วย directives)...\n", periodIndex.strftime('%b. %d, %Y was a %A'))
โค้ดเต็มและผลลัพธ์
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("\nความถี่ PeriodIndex...\n", periodIndex.freq)
print("\nความถี่ PeriodIndex เป็นสตริง...\n", periodIndex.freqstr)
print("\nการแสดงสตริง (จัดรูปแบบด้วย directives)...\n", periodIndex.strftime('%b. %d, %Y was a %A'))
PeriodIndex...
PeriodIndex(['2021', '2019', '2020', '2022'], dtype='period[A-DEC]')
ความถี่ PeriodIndex...
ความถี่ PeriodIndex เป็นสตริง...
A-DEC
การแสดงสตริง (จัดรูปแบบด้วย 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')