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
This exercise is part of the course
Python for R Users
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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)