set_index() in Pandas for Data Manipulation

Setting Index assigns a column as the DataFrame’s index, which can speed up lookups and organize data hierarchically. Set one or more columns as the DataFrame index with set_index(), which helps in data alignment and lookup.

Let us see an example to create an index in Pandas:

# Setting index using set_index()

import pandas as pd

data = {'ID': [101,102,103,104,105],
        'Name': ['John', 'David', 'Steve', 'Chris', 'Will']
        }

df = pd.DataFrame(data)

print(df)

# Set the ID column as an index
df.set_index('ID', inplace=True)

print(df)

Output

    ID   Name
0  101   John
1  102  David
2  103  Steve
3  104  Chris
4  105   Will
      Name
ID        
101   John
102  David
103  Steve
104  Chris
105   Will

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

Create Pivot Table with Pandas
Create MultiIndex in Pandas for Data Manipulation
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment