How to Use append in pandas: Syntax, Example, and Tips
In pandas, use the
append() method to add rows from one DataFrame or Series to another. It returns a new DataFrame with the combined data without changing the original. Note that append() is deprecated since pandas 1.4.0; use pd.concat() instead for newer code.Syntax
The append() method is called on a DataFrame to add rows from another DataFrame or Series. It returns a new DataFrame with the rows added.
other: The DataFrame or Series to append.ignore_index: IfTrue, the new DataFrame will reset the index to default integers.verify_integrity: IfTrue, checks for duplicate indexes and raises an error if found.sort: IfTrue, sorts columns if columns differ.
python
DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=False)
Example
This example shows how to append one DataFrame to another and reset the index to get a clean combined DataFrame.
python
import pandas as pd # Create first DataFrame df1 = pd.DataFrame({ 'Name': ['Alice', 'Bob'], 'Age': [25, 30] }) # Create second DataFrame df2 = pd.DataFrame({ 'Name': ['Charlie', 'Diana'], 'Age': [35, 40] }) # Append df2 to df1 and reset index combined = df1.append(df2, ignore_index=True) print(combined)
Output
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
3 Diana 40
Common Pitfalls
One common mistake is expecting append() to modify the original DataFrame. It does not; it returns a new DataFrame. Another issue is using append() repeatedly in a loop, which is inefficient. Instead, collect DataFrames in a list and use pd.concat() once.
Also, since pandas 1.4.0, append() is deprecated and will be removed in future versions. Use pd.concat() for better performance and future compatibility.
python
import pandas as pd # Inefficient way (legacy) df = pd.DataFrame({'A': [1, 2]}) for i in range(3, 6): df = df.append({'A': i}, ignore_index=True) print(df) # Efficient way using concat frames = [pd.DataFrame({'A': [1, 2]})] for i in range(3, 6): frames.append(pd.DataFrame({'A': [i]})) df_concat = pd.concat(frames, ignore_index=True) print(df_concat)
Output
A
0 1
1 2
2 3
3 4
4 5
A
0 1
1 2
2 3
3 4
4 5
Quick Reference
Summary tips for using append() in pandas:
- Use
append()to add rows from another DataFrame or Series. - It returns a new DataFrame; original is unchanged.
- Set
ignore_index=Trueto reset the index after appending. - For multiple appends, use
pd.concat()for better speed. - Note:
append()is deprecated; preferpd.concat().
Key Takeaways
The append() method adds rows from one DataFrame to another and returns a new DataFrame.
append() does not change the original DataFrame; assign the result to a new variable.
Use ignore_index=True to reset the index after appending for a clean DataFrame.
Avoid using append() repeatedly in loops; use pd.concat() for better performance.
append() is deprecated since pandas 1.4.0; use pd.concat() for future-proof code.