Changing row index of pandas dataframe

Given a pandas dataframe, we have to change the index of rows of a pandas DataFrame. By Pranit Sharma Last updated : October 05, 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.

Problem statement

Suppose we are given a dataframe with a column containing some values, obviously each of these values will act as a separate row.

Also, we are given that each of these rows has the same index, and we need to change these indexes to some specific values.

Changing row index

For this purpose, we have the simplest and quickest method which is to access the indexes of the dataframe using df.index() method, we will use df.index() method and assign it a new range of indexes.

Let us understand with the help of an example,

Python program to change the index of rows of a pandas DataFrame

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {'A':[1,2,3,4,5,6,7,8,9,10]}

# Creating dataframe
df = pd.DataFrame(d,index=[0,0,0,0,0,0,0,0,0,0])

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

# Changing df indexes
df.index = range(10)

# Display new df
print("New DataFrame:\n",df)

Output

The output of the above program is:

Example: Changing row index of pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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