0
0
PandasHow-ToBeginner · 3 min read

How to Add a Row to DataFrame in pandas: Simple Guide

To add a row to a pandas DataFrame, use df.loc with a new index or df.append() with a dictionary or Series representing the row. The loc method modifies the DataFrame in place, while append() returns a new DataFrame with the added row.
📐

Syntax

There are two common ways to add a row to a pandas DataFrame:

  • Using loc: df.loc[new_index] = new_row_data adds a row at the specified index.
  • Using append(): df = df.append(new_row, ignore_index=True) returns a new DataFrame with the row added.

new_row_data can be a list, dictionary, or pandas Series matching the DataFrame columns.

python
df.loc[new_index] = new_row_data

df = df.append(new_row, ignore_index=True)
💻

Example

This example shows how to add a new row to a DataFrame using both loc and append(). It demonstrates adding a row with a dictionary and updating the DataFrame.

python
import pandas as pd

# Create initial DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    'Age': [25, 30]
})

# Add row using loc
df.loc[2] = {'Name': 'Charlie', 'Age': 35}

# Add row using append
new_row = {'Name': 'Diana', 'Age': 28}
df = df.append(new_row, ignore_index=True)

print(df)
Output
Name Age 0 Alice 25 1 Bob 30 2 Charlie 35 3 Diana 28
⚠️

Common Pitfalls

Common mistakes when adding rows include:

  • Using append() without assigning back to the DataFrame, which does not change the original.
  • Adding rows with mismatched columns causing missing or NaN values.
  • Using loc with an existing index overwrites that row instead of adding a new one.
python
import pandas as pd

df = pd.DataFrame({'A': [1, 2]})

# Wrong: append without assignment (no change)
df.append({'A': 3}, ignore_index=True)
print(df)  # Still original

# Right: assign back
df = df.append({'A': 3}, ignore_index=True)
print(df)
Output
A 0 1 1 2 A 0 1 1 2 2 3
📊

Quick Reference

MethodUsageModifies Original?Notes
locdf.loc[new_index] = new_row_dataYesAdds or overwrites row at index
appenddf = df.append(new_row, ignore_index=True)NoReturns new DataFrame, slower for many rows

Key Takeaways

Use df.loc[new_index] = new_row_data to add a row in place by specifying the index.
Use df = df.append(new_row, ignore_index=True) to add a row and get a new DataFrame.
Always assign the result of append() back to the DataFrame to keep changes.
Ensure new row data matches DataFrame columns to avoid missing values.
Adding rows one by one with append() can be slow; consider collecting rows and concatenating.