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

Python Pandas - สร้าง DataFrame จาก DateTimeIndex โดยไม่รวม Index

หากต้องการสร้าง DataFrame จาก DateTimeIndex โดย ไม่รวม index เดิม สามารถใช้เมธอด DatetimeIndex.to_frame() พร้อมพารามิเตอร์ index=False

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

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

import pandas as pd

2. สร้าง DatetimeIndex

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 โดยไม่รวม index เดิม

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

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

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 เดิมเป็นคอลัมน์
print("\nDateTimeIndex to DataFrame...\n", 
      datetimeindex.to_frame(index=False))

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

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...
                            0
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

ความแตกต่างจากบทความก่อนหน้า: เมื่อไม่ระบุพารามิเตอร์ name คอลัมน์ผลลัพธ์จะมีชื่อเป็นตัวเลข 0 (ค่าเริ่มต้น) แทนชื่อที่กำหนดเอง

คุณสมบัติเพิ่มเติมของ to_frame()

# รวม index เข้าไปด้วย (ค่าเริ่มต้น)
df_with_index = datetimeindex.to_frame(index=True)
# หรือ
df_with_index = datetimeindex.to_frame()

# เปลี่ยนชื่อคอลัมน์และรวม index
df_custom = datetimeindex.to_frame(index=True, name='MyDateTime')