Change multiple columns in pandas dataframe to datetime

Given a pandas dataframe, we have to change multiple columns to datetime. By Pranit Sharma Last updated : October 03, 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.

Datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually date is present in the format of 'yy-mm-dd' and time is present in the format of 'HH:MM:SS'.

Problem statement

Suppose, we are given a DataFrame with multiple columns and we need to convert some of the columns to datetime type.

Changing multiple columns in pandas dataframe to datetime

For this purpose, we will use pandas.DataFrame.iloc property inside which we will pass some sliced columns.

i in pandas.DataFrame.iloc stands for index. This is also a data selection method but here, we need to pass the proper index as a parameter to select the required row or column. Indexes are nothing but the integer value ranging from 0 to n-1 which represents the number of rows or columns. We can perform various operations using pandas.DataFrame.iloc property. Inside pandas.DataFrame.iloc property, the index value of the row comes first followed by the number of columns.

Let us understand with the help of an example,

Python program to change multiple columns in pandas dataframe to datetime

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':['a','b','c','d','e'],
    'B':['abc','kfd','kec','sde','akw']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Checking the string
df['C'] = df.apply(lambda x: x.A in x.B, axis=1)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Change multiple columns in pandas dataframe to datetime

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.