Insert a row to pandas dataframe
How can you insert a new row into a pandas DataFrame in Python?
What methods are available to add row data efficiently, whether at the beginning, middle, or end of the DataFrame?
There are several ways to insert a new row into a pandas DataFrame, depending on whether you want to append at the end or place the row at a specific position. Pandas provides flexible methods, but it’s important to choose the most efficient one for performance, especially with large datasets.
Common Methods to Add a Row
1️ Append a Row (Recommended for small additions)
Using loc when adding at the bottom:
df.loc[len(df)] = ["Alice", 25, "USA"]2️ Insert at a Specific Index
You can use pd.concat() to place the new row anywhere:
new_row = pd.DataFrame([["Bob", 30, "UK"]], columns=df.columns)
df = pd.concat([df.iloc[:2], new_row, df.iloc[2:]]).reset_index(drop=True)3️ Using .append() (Deprecated in newer pandas)
Older code may still use:
df = df.append(new_row, ignore_index=True)But avoid this method in recent pandas versions.
Important Notes
- Concat operations are more expensive on larger DataFrames because they create new memory copies.
- For frequent row additions, collect rows in a list first → convert to DataFrame later.
- Always ensure columns match in order and number when inserting.
In summary, pandas allows multiple ways to insert rows, but the best method depends on performance needs: loc for quick bottom insertions, concat for more control, and batching rows for larger data operations.