In this tutorial we will learn how to solve attribute errors related to the Pandas DataFrame object.
Why do we get DataFrame attributeerror exceptions?
Pandas raises the attribute error exception when we try to invoke a method or property that doesn’t exist for a DataFrame.
Example # 1: Calling wrong DataFrame methods
Here’s a simple example – assume that you would like to concatenate two or more DataFrames. You write the following code:
your_df1.concat(your_df2)
You will receive the following exception:
AttributeError: 'DataFrame' object has no attribute 'concat'
Fixing this is relatively easy. Pass a list of DataFrames to the pd.concat function.
pd.concat([df1, df2])
You will receive a similar error when trying to call functions such as map, to_datetime, to_frame, write, unique, str, and so forth using a dot notation on DataFrames.
Example # 2 – Calling wrong DataFrame properties
Another example is that you try to set a DataFrame property in the wrong way. For example, you try to rename a DataFrame in the following manner:
yourdf1.name = 'yourdf2'
You can fix this by using something like:
yourdf2 = yourdf1
# or - to create a deep copy
yourdf2 = yourdf1.copy()
Example # 3: Referencing a wrong column label with dot notation
Seems that many people still use the dot notation instead of brackets when referring to a pandas column.
your_df.your_col_label
Instead of using the bracket notation:
your_df['your_col_label']
You will receive an attribute error when using the dot notation and making a typo in your column label / name:
your_df.your_wrong_col_label
To fix this, simply use the DataFrame columns property to ensure that the column label written in your code is correctly spelled.
Follow up learning
How to solve the DataFrame not callable exception in Python?