To insert a row at the top or a specific index on DataFrame you can achieve it bt using slicing or concat
:
(1) Using pd.concat()
with a list
vals = [1, 2]
pd.concat([pd.DataFrame([vals], columns=df.columns), df], ignore_index=True)
(2) Using df.loc
with manual index shift and sort
df.loc[-1] = [1,2]
df.index = df.index + 1
df = df.sort_index()
1: Insert a Row on top of Pandas DataFrame
Let's say you have a simple DataFrame:
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35]
})
If you want to insert a new row hen you can use the following syntax:
vals = ['David', 28]
pd.concat([pd.DataFrame([vals], columns=df.columns), df], ignore_index=True)
Result:
name | age | |
---|---|---|
0 | David | 28 |
1 | Alice | 25 |
2 | Bob | 30 |
3 | Charlie | 35 |
Insert at Position (e.g., Index 1)
new_row = pd.DataFrame({'name': ['David'], 'age': [28]})
pd.concat([df.iloc[:1], new_row, df.iloc[1:]]).reset_index(drop=True)
Output:
name | age | |
---|---|---|
0 | David | 28 |
1 | Alice | 25 |
2 | Bob | 30 |
3 | Charlie | 35 |
Tips
- Use
reset_index(drop=True)
after insertion to maintain continuous indexing. - For appending to the end, use:
df.loc[len(df)] = vals
ordf = pd.concat([df, new_row])