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

Python Pandas - สร้าง DataFrame จาก DateTimeIndex และเปลี่ยนชื่อคอลัมน์

หากต้องการสร้าง DataFrame จาก DateTimeIndex และเปลี่ยนชื่อคอลัมน์ผลลัพธ์ สามารถใช้เมธอด DatetimeIndex.to_frame() พร้อมพารามิเตอร์ name

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้าง DatetimeIndex

สร้างด้วย pd.date_range() ระบุ start, periods, timezone, และ freq

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624', 
    periods=5, 
    tz='Australia/Adelaide', 
    freq='40S'
)

3. แสดง DateTimeIndex

print("DateTimeIndex...\n", datetimeindex)

4. สร้าง DataFrame และกำหนดชื่อคอลัมน์

print("\nDateTimeIndex to DataFrame...\n", 
      datetimeindex.to_frame(index=False, name='DateTimeData'))

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# DatetimeIndex with period 5 and frequency as S i.e. seconds
# timezone is Australia/Adelaide
datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624', 
    periods=5, 
    tz='Australia/Adelaide', 
    freq='40S'
)

# แสดง DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# แสดง DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# สร้าง DataFrame จาก DateTimeIndex
# index=False: ไม่ตั้งค่า index เดิมเป็นคอลัมน์
# name='DateTimeData': ตั้งชื่อคอลัมน์ผลลัพธ์
print("\nDateTimeIndex to DataFrame...\n", 
      datetimeindex.to_frame(index=False, name='DateTimeData'))

ผลลัพธ์ที่คาดหวัง

DateTimeIndex... DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30', '2021-10-18 07:21:12.261811624+10:30', '2021-10-18 07:21:52.261811624+10:30', '2021-10-18 07:22:32.261811624+10:30', '2021-10-18 07:23:12.261811624+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency... <40 * Seconds>
DateTimeIndex to DataFrame...
            DateTimeData
0 2021-10-18 07:20:32.261811624+10:30
1 2021-10-18 07:21:12.261811624+10:30
2 2021-10-18 07:21:52.261811624+10:30
3 2021-10-18 07:22:32.261811624+10:30
4 2021-10-18 07:23:12.261811624+10:30

คำอธิบายเพิ่มเติม:

  • index=False: ไม่นำ index ของ DateTimeIndex ไปเป็นคอลัมน์ใน DataFrame
  • name='DateTimeData': ตั้งชื่อคอลัมน์เดียวของ DataFrame ผลลัพธ์
  • Timezone Australia/Adelaide (UTC+10:30) ถูกเก็บรักษาไว้ในข้อมูล
  • Frequency 40S หมายถึง ทุก 40 วินาที