How to set column as date index?

Given a pandas dataframe, we have to set column as date index.
Submitted by Pranit Sharma, on October 15, 2022

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.

Problem statement

Suppose we are given a DataFrame with two columns date and value, date column contains string characters and the value columns contain integer values. We need to set the index of DataFrame as the values of the date column.

Setting column as date index

To set column as date index, we will first convert the type of values of the date column into datetime and then we will use pandas.DataFrame.set_index() method inside which we will pass the date column so that all the values of date columns would be converted to index values.

Let us understand with the help of an example,

Python program to set column as date index

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'date':['07-12-2001','08-11-2002','09-10-2003','10-09-2004','11-08-2005'],
    'value':[3,6,9,1,0]
}

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

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

# Getting information of DataFrame
print("Information:\n",df.info(),"\n")

# Converting date column to datetime
df['date'] = pd.to_datetime(df['date'])

# Resetting the index
df.set_index('date', inplace=True)

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

Output

Example: Set column as date index

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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