Changing row index of pandas dataframe

Given a pandas dataframe, we have to change the index of rows of a pandas DataFrame.
Submitted by Pranit Sharma, on November 21, 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.

Changing row index

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.

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 code 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:

Example: Changing row index of pandas dataframe

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.