Home »
Python »
Python Programs
Add a row at top in pandas dataframe
Given a pandas dataframe, we have to add a row at top in it.
By Pranit Sharma Last updated : October 02, 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.
Adding a row at top in pandas dataframe
We will first create a DataFrame, we will then use the pandas.DataFrame.loc property to get the location of where we want to add a row.
We will first fix this series at the last position and after that, we will rearrange the index of the DataFrame.
Let us understand with the help of an example,
Python program to add a row at top in pandas dataframe
# Importing pandas package
import pandas as pd
# Creating two dictionaries
d = {
'Name':['Ram','Shyam','Seeta','Geeta'],
'Age':[19,21,23,20],
'Department':['IT','Sales','Marketing','Sales']
}
# Creating DataFrame
df = pd.DataFrame(d)
# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")
# Adding a new row
df.loc[-1] = ['Danny', 22, 'Accounts']
df.index = df.index + 1
df.sort_index(inplace=True)
# Display result
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »