MulaiMulai sekarang secara gratis

Dates (II)

Instead of converting the type of a column after importing the data, you can import the data while parsing the dates correctly. To do this, you can pass the parse_dates argument of pd.read_csv() a list of column names that should be imported as dates. Once the date column is imported as the correct type (datetime64), you can make use of the .dt accessor along with the .year, .month, and .day attributes to can access the year, month, and day from these dates.

# Access year
df['Date'].dt.year

# Access month
df['Date'].dt.month

# Access day
df['Date'].dt.day

Latihan ini adalah bagian dari kursus

Python for R Users

Lihat Kursus

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

import pandas as pd

# Load the dataset and ensure Date column is imported as datetime
ebola = pd.read_csv('country_timeseries.csv', parse_dates=____)

# Inspect the Date column
print(ebola['Date'].dtype)
Edit dan Jalankan Kode