Home »
Python »
Python Programs
How to check if a column in a pandas dataframe is of type datetime or a numerical?
Given a pandas dataframe, we have to check if its column is of type datetime or a numerical.
By Pranit Sharma Last updated : October 06, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
In a programming language, data types are the particular format in which a value is being stored. A data type is a kind of data item, which represents what values it can take, the programming language used, or the operations that can be performed on it.
Problem statement
Suppose we are given a dataframe and we need to filter the values based on whether they are of dtype date or not.
Checking whether a dataframe's column is of type datetime or a numerical
We will select the dataframe column based on data type with the help of pandas.dataframe.select_dtypes() method inside which we will pass a parameter called include = [ ]. This parameter itself accepts the list inside which we will pass the particular data type.
Let us understand with the help of an example,
Python program to check if a column in a pandas dataframe is of type datetime or a numerical
# Importing pandas package
import pandas as pd
# Import numpy
import numpy as np
# Creating a dictionary
d1 = {
'int':[1,2,3,4,5],
'float':[1.5,2.5,3.5,4.5,5.5],
'Date':['2017-02-01','2017-03-02','2017-04-03','2017-05-04','2017-06-05'],
'boolean':[True,False,True,False,True]
}
# Creating DataFrame
df = pd.DataFrame(d1)
# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")
# Converting date column to datetime
df['Date'] = pd.to_datetime(df['Date'])
# Selcting date columns
res = df.select_dtypes(include=[np.datetime64])
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »