Pandas: วิธีแปลงดัชนีเป็นวันที่/เวลา
คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อแปลงคอลัมน์ดัชนีของ DataFrame แพนด้าเป็นรูปแบบวันที่และเวลา:
df. index = pd. to_datetime ( df.index )
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: แปลงคอลัมน์ดัชนีเป็น Datetime ใน Pandas
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับการขายผลิตภัณฑ์ในร้านค้า:
import pandas as pd #createDataFrame df = pd. DataFrame ({' time ': ['4-15-2022 10:15', '5-19-2022 7:14', '8-01-2022 1:14', '6-14-2022 9:45', '10-24-2022 2:58', '12-13-2022 11:03'], ' product ': ['A', 'B', 'C', 'D', 'E', 'F'], ' sales ': [12, 25, 23, 18, 14, 10]}) #set 'time' column as index df = df. set_index (' time ') #view DataFrame print (df) product sales time 4-15-2022 10:15 A 12 5-19-2022 7:14 B 25 8-01-2022 1:14 C 23 6-14-2022 9:45 D 18 10-24-2022 2:58 E 14 12-13-2022 11:03 F 10
ตอนนี้ สมมติว่าเราพยายามสร้างคอลัมน์ใหม่ที่มีเวลาในคอลัมน์ดัชนี:
#attempt to create new column that contains hour of index column
df[' hour '] = df. index . hour
AttributeError: 'Index' object has no attribute 'hour'
เราได้รับข้อผิดพลาดเนื่องจากคอลัมน์ดัชนีไม่อยู่ในรูปแบบ datetime ดังนั้นจึงไม่มีแอตทริบิวต์ ‘time’
เพื่อหลีกเลี่ยงข้อผิดพลาดนี้ เราสามารถใช้ฟังก์ชัน pandas to_datetime() เพื่อแปลงคอลัมน์ดัชนีเป็นรูปแบบ datetime:
#convert index column to datetime format
df. index = pd. to_datetime ( df.index )
#create new column that contains hour of index column
df[' hour '] = df. index . hour
#view updated DataFrame
print (df)
product sales hour
time
2022-04-15 10:15:00 At 12 10
2022-05-19 07:14:00 B 25 7
2022-08-01 01:14:00 C 23 1
2022-06-14 09:45:00 D 18 9
2022-10-24 02:58:00 E 14 2
2022-12-13 11:03:00 F 10 11
การใช้ฟังก์ชัน to_datetime() ทำให้เราสามารถแปลงคอลัมน์ดัชนีเป็นรูปแบบวันที่และเวลาได้
ดังนั้นเราจึงสามารถสร้างคอลัมน์ใหม่ที่เรียกว่า เวลา ได้สำเร็จซึ่งมีเวลาชั่วโมงในคอลัมน์ดัชนีโดยไม่ได้รับข้อผิดพลาดใด ๆ
หมายเหตุ : คุณสามารถดูเอกสารฉบับเต็มของฟังก์ชัน to_datetime() ของ pandas ได้ที่นี่
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีสร้างช่วงวันที่ใน Pandas
วิธีแปลงการประทับเวลาเป็นวันที่/เวลาใน Pandas
วิธีคำนวณความแตกต่างระหว่างวันที่สองวันในหมีแพนด้า