Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add a row at top in pandas DataFrame
Adding a row at the top of a Pandas DataFrame is a common operation when you need to insert headers, summary rows, or new data at the beginning. There are several methods to achieve this − using pd.concat(), loc[] with index manipulation, or iloc slicing.
Create a Sample DataFrame
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Delhi', 'Mumbai', 'Pune']
})
print("Original DataFrame:")
print(df)
Original DataFrame:
Name Age City
0 Alice 25 Delhi
1 Bob 30 Mumbai
2 Charlie 35 Pune
Method 1: Using pd.concat()
Create the new row as a DataFrame and concatenate it at the top ?
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Delhi', 'Mumbai', 'Pune']
})
# New row as a DataFrame
new_row = pd.DataFrame({'Name': ['Dave'], 'Age': [28], 'City': ['Hyderabad']})
# Concat at top and reset index
df = pd.concat([new_row, df], ignore_index=True)
print(df)
Name Age City
0 Dave 28 Hyderabad
1 Alice 25 Delhi
2 Bob 30 Mumbai
3 Charlie 35 Pune
Method 2: Using loc[] with Index Shift
Assign a new index position and sort to place the row at the top ?
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Delhi', 'Mumbai', 'Pune']
})
# Shift existing index by 1
df.index = df.index + 1
# Insert at index 0
df.loc[0] = ['Dave', 28, 'Hyderabad']
# Sort by index to bring row 0 to top
df = df.sort_index()
print(df)
Name Age City
0 Dave 28 Hyderabad
1 Alice 25 Delhi
2 Bob 30 Mumbai
3 Charlie 35 Pune
Method 3: Using _append() with Dictionary
Prepend by reversing concat order with a dictionary converted to DataFrame ?
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Delhi', 'Mumbai', 'Pune']
})
# Create row from dictionary
new_row = pd.DataFrame([{'Name': 'Dave', 'Age': 28, 'City': 'Hyderabad'}])
df = pd.concat([new_row, df]).reset_index(drop=True)
print(df)
Name Age City
0 Dave 28 Hyderabad
1 Alice 25 Delhi
2 Bob 30 Mumbai
3 Charlie 35 Pune
Comparison
| Method | Modifies Original? | Resets Index? | Best For |
|---|---|---|---|
pd.concat() |
No (returns new df) | With ignore_index=True
|
Most common, clean approach |
loc[] + sort_index |
Yes | Manual sort needed | When index manipulation is acceptable |
Dict + concat
|
No | With reset_index(drop=True)
|
Quick insertion from dictionary |
Conclusion
Use pd.concat([new_row, df], ignore_index=True) as the most straightforward method to add a row at the top of a DataFrame. The index shift method works for in-place modification. Always use ignore_index=True or reset_index(drop=True) to maintain clean sequential indexing.
