In Pandas, rows can be added at different positions in a DataFrame. To insert a new row at the beginning, we can use the concat() function to combine the new row with the existing DataFrame while maintaining the desired order.
- We can use the pandas.concat() function to place a new row before all existing rows.
- The ignore_index parameter can be set to True to generate a new sequential index for the resulting DataFrame.
Syntax
pd.concat( [ new_row, df ] , ignore_index=True )
Parameters:
- new_row: A DataFrame containing the row to be inserted.
- df: Existing Dataframe.
- ignore_index: Creates a new sequential index starting from 0.
1. Importing Pandas and Create a DataFrame
First, Import the pandas library and create a DataFrame containing sample data.
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob", "David"],
"Age": [25, 30, 28],
"City": ["Delhi", "Mumbai", "Pune"]
})
print(df)
Output
Name Age City 0 Alice 25 Delhi 1 Bob 30 Mumbai 2 David 28 Pune
Explanation:
- DataFrame contains three rows and three columns.
- Default index starts at 0 and increases sequentially.
2. Creating New Row
Create another DataFrame containing the record that needs to appear at the top.
new_row = pd.DataFrame([{
"Name": "Charlie",
"Age": 22,
"City": "Noida"
}])
Explanation:
- Dictionary defines the values for each column.
- Wrapping the dictionary in a list creates a DataFrame containing one row.
- Column names should match those of the existing DataFrame.
3. Inserting Row at Beginning
Use pd.concat() to combine the new row with the existing DataFrame.
df = pd.concat([new_row, df], ignore_index=True)
print(df)
Explanation:
- Placing new_row before df ensures that the new record appears first.
- ignore_index=True assigns fresh index labels to every row.
- Assigning the result to df updates the variable with the combined DataFrame.
Complete Program
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob", "David"],
"Age": [25, 30, 28],
"City": ["Delhi", "Mumbai", "Pune"]
})
new_row = pd.DataFrame([{
"Name": "Charlie",
"Age": 22,
"City": "Noida"
}])
df = pd.concat([new_row, df], ignore_index=True)
print(df)
Output
Name Age City 0 Charlie 22 Noida 1 Alice 25 Delhi 2 Bob 30 Mumbai 3 David 28 Pune

