In this tutorial, we will look at how to convert a datetime type column to a category type column in Pandas and apply common datetime operations.
How to convert datetime
column to category
type column in Pandas?
You can use the Pandas astype()
function to change the type of a column. To convert a column to category
dtype, pass “category” as an argument. The following is the syntax –
df["Col"] = df["Col"].astype("category")
It converts the column to category
type. You can still access common datetime attributes (like month
, year
, etc.) and functions with the help of the .dt
accessor.
Examples
Let’s look at some examples of converting a datetime column to a categorical column in Pandas. First, we’ll create a sample dataframe that we will be using throughout this tutorial.
import pandas as pd # create a dataframe df = pd.DataFrame({ "Name": ["Tim", "Sarah", "Hasan", "Jyoti", "Jack"], "DOB": ["1999-04-02", "2001-12-23", "1998-07-13", "2000-01-01", "2001-08-29"] }) # convert "DOB" to datetime df["DOB"] = pd.to_datetime(df["DOB"]) # display the dataframe print(df)
Output:
Name DOB 0 Tim 1999-04-02 1 Sarah 2001-12-23 2 Hasan 1998-07-13 3 Jyoti 2000-01-01 4 Jack 2001-08-29
We now have a dataframe containing the name and the date of birth of some students enrolled in a university.
Note that the “DOB” column is a datetime column.
Let’s change the type of the “DOB” column to category
with the help of the astype()
function.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# convert "DOB" to category type df["DOB"] = df["DOB"].astype("category") # display the column print(df["DOB"])
Output:
0 1999-04-02 1 2001-12-23 2 1998-07-13 3 2000-01-01 4 2001-08-29 Name: DOB, dtype: category Categories (5, datetime64[ns]): [1998-07-13, 1999-04-02, 2000-01-01, 2001-08-29, 2001-12-23]
You can see that the “DOB” column is now of category
type.
Accessing datetime attributes on a category column with datetime values
You can use the .dt
accessor on Pandas category columns with datetime values to access common datetime attributes.
For example, let’s get the year from the “DOB” column. For this, use the year
attribute with the help of the .dt
accessor.
# get year for DOB print(df["DOB"].dt.year)
Output:
0 1999 1 2001 2 1998 3 2000 4 2001 Name: DOB, dtype: int64
You can see that we get the year for all the dates in the “DOB” column. Note that the data type of the resulting series is integer and not category
.
You might also be interested in –
- Pandas – Convert Category Type Column to String
- Pandas – Change Column Type to Category
- Get List of Categories in Pandas Category Column
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.