pandas
dataframe
Python
data manipulation
row insertion

Insert a row to pandas dataframe

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Adding a row to a pandas DataFrame is common, but the "best" method depends on where the row should go and how often you are doing it. Pandas is column-oriented, so row insertion is not a special fast-path operation the way it might be in a spreadsheet.

Append a Row with loc

If your DataFrame uses a simple integer index and you want to add a row at the end, loc is usually the clearest option.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    [
5        ["Alice", 25, "New York"],
6        ["Bob", 30, "Los Angeles"],
7    ],
8    columns=["name", "age", "city"],
9)
10
11df.loc[len(df)] = ["Charlie", 35, "Chicago"]
12
13print(df)

Output:

text
1      name  age         city
20    Alice   25     New York
31      Bob   30  Los Angeles
42  Charlie   35      Chicago

This works because len(df) is the next unused label when the index is 0, 1, 2, .... It is concise and readable for single-row appends.

You can also insert with a dictionary if you prefer matching by column name:

python
df.loc[len(df)] = {"name": "Dora", "age": 28, "city": "Austin"}

That is safer when the DataFrame has many columns and column order is easy to get wrong.

Insert a Row at a Specific Position with concat

There is no dedicated "insert row at position 2" API for DataFrames. The common pattern is to split the frame and concatenate the parts with a one-row DataFrame in the middle.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    [
5        ["Alice", 25, "New York"],
6        ["Charlie", 35, "Chicago"],
7    ],
8    columns=["name", "age", "city"],
9)
10
11new_row = pd.DataFrame(
12    [{"name": "Bob", "age": 30, "city": "Los Angeles"}]
13)
14
15top = df.iloc[:1]
16bottom = df.iloc[1:]
17
18df = pd.concat([top, new_row, bottom], ignore_index=True)
19
20print(df)

This is explicit and works well when row position matters for presentation or later processing. ignore_index=True tells pandas to rebuild the row labels from zero upward, which avoids duplicate or surprising index values.

Add Many Rows Efficiently

If you need to insert rows repeatedly, avoid growing the DataFrame one row at a time in a loop. That forces pandas to allocate new objects over and over again.

A better pattern is to collect rows first and concatenate once:

python
1import pandas as pd
2
3df = pd.DataFrame(columns=["name", "age", "city"])
4
5rows = [
6    {"name": "Alice", "age": 25, "city": "New York"},
7    {"name": "Bob", "age": 30, "city": "Los Angeles"},
8    {"name": "Charlie", "age": 35, "city": "Chicago"},
9]
10
11df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
12
13print(df)

This scales much better and keeps the code simple. If the data already exists in Python objects, building a DataFrame from the full list is usually the cleanest approach.

Choose the Method Based on the Index

The index changes the meaning of insertion. With a default integer index, loc[len(df)] usually means "append to the end." With a custom index, loc uses labels instead of positions:

python
df = pd.DataFrame(columns=["amount"])
df.loc["invoice-104"] = {"amount": 99.0}

That is valid, but it is label assignment, not positional insertion. If you need a row to appear at a certain numeric position, concat with iloc slices is the clearer solution.

Common Pitfalls

  • Using the old append habit from older examples. Modern pandas code should prefer concat.
  • Assuming loc[1] means "second row." loc is label-based, not position-based.
  • Inserting a row with missing columns, which introduces NaN values and sometimes changes dtypes.
  • Adding rows one by one inside a large loop, which is slow and memory-inefficient.
  • Forgetting ignore_index=True when combining pieces, which can leave duplicate index labels behind.

Summary

  • Use df.loc[len(df)] = ... when you want to append one row to a DataFrame with a simple integer index.
  • Use pd.concat when you need to insert a row at a specific position.
  • Build many rows in a list first and concatenate once for better performance.
  • Remember that loc works by label, while iloc works by position.
  • Pick the method that matches your index semantics, not just the shortest syntax.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.