Home >Backend Development >Python Tutorial >How to Replace Pandas' Deprecated `append` Method for Adding Rows to a DataFrame?
Error "DataFrame' object has no attribute 'append'": Using 'concat' Instead
In pandas, the 'append' method has been removed as of version 2.0 and replaced by 'concat'. This means you can no longer use DataFrame.append() to add a dictionary as a new row to a DataFrame. To resolve this error and achieve the desired functionality, you should use 'concat' instead.
Using 'concat'
To append a dictionary as a new row to a DataFrame using 'concat', follow these steps:
Convert the dictionary to a DataFrame with one row:
new_row_df = pd.DataFrame([new_row])
Concatenate the new row DataFrame with the original DataFrame:
df = pd.concat([df, new_row_df], ignore_index=True)
Alternative: Using 'loc' (with Caution)
Another option, but with some restrictions, is to use 'loc':
df.loc[len(df)] = new_row
However, note that this only works if the new index is not already present in the DataFrame (typically the case if the index is a RangeIndex).
Why Was 'append' Removed?
The 'append' method was removed because it was inefficient for repeated insertion. While 'list.append' is O(1) at each step, 'DataFrame.append' was O(n), making it slow for loops. Additionally, it created a new DataFrame for each step, leading to a quadratic behavior.
Best Practices for Repeated Insertion
If you need to repeatedly append rows to a DataFrame, it's best to collect the new items in a list, convert it to a DataFrame, and then concatenate it to the original DataFrame at the end of the loop. This approach avoids the overhead of repeated append operations.
The above is the detailed content of How to Replace Pandas' Deprecated `append` Method for Adding Rows to a DataFrame?. For more information, please follow other related articles on the PHP Chinese website!