In this tutorial, we'll see how to solve a Pandas error: AttributeError: 'DataFrame' object has no attribute 'append'.
We will also answer on the questions:
- Why is append not working in pandas?
- How do I fix pandas attribute error?
- How do you append an object to a DataFrame in Python?
- How to append a new row to Pandas DataFrame?
Why is append not working in pandas?
Pandas method append()
was deprecated in version 1.4.
So in more recent versions of Pandas 2.0, append()
is no longer used to add rows to a DataFrame. You can achieve the same result using the concat()
method.
For more information you can find: pandas.DataFrame.append
AttributeError: 'DataFrame' object has no attribute 'append'
The error: AttributeError: 'DataFrame' object has no attribute 'append' can be reproduced by the following example.
We would like to append new data to DataFrame:
A | B | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
The code is:
import pandas as pd
data = {'A': [1, 2], 'B': [3, 4]}
df = pd.DataFrame(data)
df = df.append({'A': 5, 'B': 6})
this results into error:
AttributeError: 'DataFrame' object has no attribute 'append'
Fix for AttributeError - concat
To fix the error we can use the method concat()
to append two DataFrames in Pandas.
So the append syntax:
df.append({'A': 5, 'B': 6})
should be changed to:
pd.concat([df, pd.DataFrame([{'A': 5, 'B': 6}])])
or using parameter - ignore_index=True
:
pd.concat([df, pd.DataFrame([{'A': 5, 'B': 6}])], ignore_index=True)
The above example will become:
import pandas as pd
data = {'A': [1, 3], 'B': [2, 4]}
df = pd.DataFrame(data)
pd.concat([df, pd.DataFrame([{'A': 5, 'B': 6}])], ignore_index=True)
Final result is appended new row to the original DataFrame:
A | B | |
---|---|---|
0 | 1 | 2 |
1 | 3 | 4 |
2 | 5 | 6 |
Alternative Solutions
In this section you can find several alternative solutions:
- downgrade to older Pandas version
df = df1._append(df2,ignore_index=True)
df.loc[len(df)] = new_row # only use with a RangeIndex!
pd.concat([df, df_extended])
more information and details on that error can be found on this link: Error "'DataFrame' object has no attribute 'append'"
Conclusion
To sum up, this article shows how using method concat can solve the "AttributeError: 'DataFrame' object has no attribute 'append'" Python error.