บทนำ
ใช้คุณสมบัติ DateTimeIndex.year เพื่อดึงค่าปีจาก DateTimeIndex
ขั้นตอน
1. นำเข้าไลบรารี
import pandas as pd
2. สร้าง DateTimeIndex ความถี่รายปี
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='Y')
3. ดึงค่าปี
print("\nGetting the year name..\n", datetimeindex.year)
ตัวอย่างโค้ดเต็ม
import pandas as pd
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='Y')
print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nGetting the year name..\n", datetimeindex.year)
ผลลัพธ์
DateTimeIndex...
DatetimeIndex(['2021-12-31 02:35:55+11:00', '2022-12-31 02:35:55+11:00',
'2023-12-31 02:35:55+11:00', '2024-12-31 02:35:55+11:00',
'2025-12-31 02:35:55+11:00', '2026-12-31 02:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='A-DEC')
DateTimeIndex frequency...
<YearEnd: month=12>
Getting the year name..
Int64Index([2021, 2022, 2023, 2024, 2025, 2026], dtype='int64')
คำอธิบาย
.year คืนค่าปีของแต่ละ timestamp ความถี่ 'Y' (YearEnd) ให้วันที่ 31 ธันวาคมของแต่ละปี