Home »
Python »
Python Programs
Apply Function on DataFrame Index
Given a Pandas DataFrame, we have to apply function on dataframe index.
Submitted by Pranit Sharma, on July 06, 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.
DataFrame Index
Index in pandas is just the number of rows defined in a Series or DataFrame. The index always starts from 0 to n-1 where n is the number of rows. The index is used in indexing which is a method of traversing or selecting particular rows and columns or selecting all the rows and columns.
Apply Function on DataFrame Index
To apply the function on the DataFrame index, we will access all the indexes using DataFrame.index() and put it in map() method to perform some operations on each value.
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example,
Python program to apply function on DataFrame index
# Importing pandas package
import pandas as pd
# Creating a dictionary
d ={
'Produt':['Table','Chair','Mirror'],
'Stock':[47000,66000,52000],
'Sales':[4000,6600,3200]
}
# Creating a DataFrame
df = pd.DataFrame(d,index=['BOMBAY','CHENNAI','PUNE'])
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Applying some operation on index
df.index = df.index.map(str.capitalize)
# Display modified DataFrame
print("Modified DataFrane:\n",df)
Output
The output of the above program is:
Python Pandas Programs »