Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ดึงหมายเลขเดือนจาก DateTimeIndex ด้วยความถี่อนุกรมเวลาเฉพาะ

บทนำ

ใช้คุณสมบัติ DateTimeIndex.month เพื่อดึงหมายเลขเดือน (มกราคม=1, ธันวาคม=12)

ขั้นตอน

1. นำเข้าไลบรารี

import pandas as pd

2. สร้าง DateTimeIndex ความถี่รายเดือน

datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='M')

3. ดึงหมายเลขเดือน

print("\nGetting the month number..\n", datetimeindex.month)

ตัวอย่างโค้ดเต็ม

import pandas as pd

datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='M')

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nGetting the month number..\n", datetimeindex.month)

ผลลัพธ์

DateTimeIndex...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='M')

DateTimeIndex frequency...
<MonthEnd>

Getting the month number..
Int64Index([9, 10, 11, 12, 1, 2], dtype='int64')

คำอธิบาย

.month คืนค่าหมายเลขเดือน 1-12 สำหรับแต่ละ timestamp ความถี่ 'M' ให้วันสุดท้ายของแต่ละเดือน