Add a new row to a pandas dataframe with specific index name

Given a pandas dataframe, we have to add a new row in it with specific index name. By Pranit Sharma Last updated : October 03, 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 some columns and their values and we need to add a new row this time we also need to name the index for this row.

Adding a new row to a pandas dataframe with specific index name

We will use the loc property of pandas so that we can pass our specific index inside loc and assign it a list of values. This specific index does not exist in the dataframe and hence pandas will add this new row to this index.

The loc property is a type of data selection method which takes the name of a row or column as a parameter. To perform various operations using the loc property, we need to pass the required condition of rows and columns to get the filtered data.

Let us understand with the help of an example,

Python program to add a new row to a pandas dataframe with specific index name

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Name':['Ram','Raman','Raghav'],
    'Place':['Raipur','Rampur','Ranipur'],
    'Animal':['Rat','Rat','Rat'],
    'Thing':['Rose','Rubber','Rose']
}

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

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

# Adding a specific index and its values
df.loc['d'] = ['Rick','Russia','Raccoon','Rope']

# Display Modified DataFrame
print('Modified DataFrame:\n',df)

Output

The output of the above program is:

Example: Add a new row to a pandas dataframe with specific index name

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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