Home >Backend Development >Python Tutorial >Why is `DataFrame.append` Deprecated and How Do I Add Rows to a Pandas DataFrame?

Why is `DataFrame.append` Deprecated and How Do I Add Rows to a Pandas DataFrame?

DDD
DDDOriginal
2024-12-05 21:38:15827browse

Why is `DataFrame.append` Deprecated and How Do I Add Rows to a Pandas DataFrame?

Error: 'DataFrame' Object Has No Attribute 'append'

When attempting to add a dictionary to a DataFrame object, users may encounter the error message "AttributeError: 'DataFrame' object has no attribute 'append'." While DataFrame was previously equipped with the append method, it was removed in pandas version 2.0.

Solution

To append data to a DataFrame, use the concat method instead:

df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)

Alternative Solution

If the index is a RangeIndex, the loc attribute can also be used:

df.loc[len(df)] = new_row # Note: Only use with a RangeIndex!

Why the Change?

The append method was removed because it was an inefficient operation, especially when repeated. Unlike list.append, which operates in-place, DataFrame's append created a new DataFrame. This made repeated insertion operations quadratic in time complexity.

Best Practices for Repeated Insertion

Instead of using append or concat repeatedly, collect the new items into a list and convert them to a DataFrame at the end of the loop. Then, concatenate the new DataFrame to the original.

lst = []

for new_row in items_generation_logic:
    lst.append(new_row)

# create extension
df_extended = pd.DataFrame(lst, columns=['A', 'B', 'C'])

# concatenate to original
out = pd.concat([df, df_extended])

The above is the detailed content of Why is `DataFrame.append` Deprecated and How Do I Add Rows to a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn