Python - Pandas DataFrame Add Column to Index without Resetting

Given a DataFrame, we need to add a column to index without resetting the indices. By Pranit Sharma Last updated : September 27, 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.

Rows in pandas are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update, and delete a column or row value. The index is the number of rows that ranges from 0 to n-1, so if the index is 0, it represents the first row and the n-1th index represents the last row.

Problem statement

Given a DataFrame, we need to add a column to index without resetting the indices.

Adding a column to index without resetting the indices

If we have a column with multiple values and we assign this column to the index, then all the values of the column will also become the index of this DataFrame. For adding the column to the index, we need to use DataFrame.set_index() method.

The DataFrame.set_index() method is used when we need to set the index as a series, list, or column of a DataFrame.

pandas.DataFrame.set_index() syntax:

DataFrame.set_index(
    keys, 
    drop=True, 
    append=False, 
    inplace=False, 
    verify_integrity=False
    )

Let us understand with the help of an example,

Python program to add a column to index without resetting the indices

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':range(10),
    'B':range(10),
    'C':range(10)
}

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

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

# Adding a new column
df['D'] = range(10)

# Setting index
df.set_index(['A','B','D'], inplace=True)

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

Output

The output of the above program is:

Example: Add Column to Index without Resetting

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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