Python - How to add an extra row to a pandas dataframe?

Given a Pandas DataFrame, we have to add an extra row in it. 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 the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows 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.

Problem statement

Given a Pandas DataFrame, we have to add an extra row in it.

Adding an extra row to pandas DataFrame

To add an extra row to pandas DataFrame, we will first create an empty DataFrame with multiple columns, since this DataFrame has a length of 0, we will append some values to the 0th index of this DataFrame. We know that the index works for rows and hence in this way we will be able to add an extra row to pandas DataFrame.

We will access the 0th index of the DataFrame with the help of the DataFrame.loc property. The DataFrame.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 DataFrame.loc property, we need to pass the required condition of rows and columns to get the filtered data.

On the basis of a certain condition, we can filter the DataFrame values, and also we can update these values, hence DataFrame.loc property is also useful in updating values when a certain condition is satisfied.

Let us understand with the help of an example,

Python program to add an extra row to a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating an empty DataFrame
df = pd.DataFrame(columns=['Name','Age','City'])

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

# Adding new row
df.loc[len(df)]=['Pranit Sharma', 21, 'Gwalior']

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

Output

The output of the above program is:

Example: Add an extra row to a dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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