Pandas: สร้างคอลัมน์วันที่โดยเริ่มจากปี เดือน และวัน
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อสร้างคอลัมน์วันที่จากคอลัมน์ปี เดือน และวันใน DataFrame ของแพนด้า:
df[' date '] = pd. to_datetime (dict(year=df. year , month=df. month , day=df. day ))
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: สร้างคอลัมน์วันที่จากปี เดือน และวันใน Pandas
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งแสดงยอดขายของบริษัทในวันที่ต่างกัน:
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' year ': [2021, 2022, 2022, 2022, 2022, 2022, 2022, 2022],
' month ': [7, 1, 1, 2, 5, 10, 11, 12],
' day ': [4, 15, 25, 27, 27, 24, 10, 18],
' sales ': [140, 200, 250, 180, 130, 87, 90, 95]})
#view DataFrame
print (df)
year month day sales
0 2021 7 4 140
1 2022 1 15 200
2 2022 1 25 250
3 2022 2 27 180
4 2022 5 27 130
5 2022 10 24 87
6 2022 11 10 90
7 2022 12 18 95
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้างคอลัมน์ใหม่ที่เรียกว่า date ซึ่งรวมค่าของคอลัมน์ ปี เดือน และ วัน ใน DataFrame เพื่อสร้างวันที่สำหรับแต่ละแถว:
#create date columns from year, month, and day columns
df[' date '] = pd. to_datetime (dict(year=df. year , month=df. month , day=df. day ))
#view updated DataFrame
print (df)
year month day sales date
0 2021 7 4 140 2021-07-04
1 2022 1 15 200 2022-01-15
2 2022 1 25 250 2022-01-25
3 2022 2 27 180 2022-02-27
4 2022 5 27 130 2022-05-27
5 2022 10 24 87 2022-10-24
6 2022 11 10 90 2022-11-10
7 2022 12 18 95 2022-12-18
โปรดทราบว่าคอลัมน์ วัน ที่ประกอบด้วยค่าวันที่ตามค่าใน คอลัมน์ปี เดือน และ วัน ในแต่ละแถว
หากเราใช้ df.info() เพื่อรับข้อมูลเกี่ยวกับแต่ละคอลัมน์ใน DataFrame เราจะเห็นว่าคอลัมน์ วัน ที่ใหม่มีประเภทข้อมูล datetime64 :
#display information about each column in DataFrame
df. info ()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 year 8 non-null int64
1 month 8 non-null int64
2 day 8 non-null int64
3 dirty 8 non-null int64
4 date 8 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(4)
memory usage: 388.0 bytes
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีบวกและลบวันจากวันที่ใน Pandas
วิธีเลือกแถวระหว่างวันที่สองวันใน Pandas
วิธีคำนวณความแตกต่างระหว่างวันที่สองวันในหมีแพนด้า