In case you get the error – AttributeError: ‘DataFrame’ object has no attribute ‘rows’, it means you’re trying to access data in a way that is not valid for a pandas DataFrame.
Table of Content
What is a DataFrame?
The pandas DataFrame is like a table where that data is placed in rows and columns. It’s one of the most heavily used structures to work on data in Python.
Why Does the Error Happen?
DataFrame doesn’t contain a .rows attribute in pandas. Thus, when Python tries to access .rows to get rows from a DataFrame, it doesn’t know what you’re pointing to and raises an error.
How to Fix It?
To get rows from a DataFrame, there are proper ways:
1. Using .iloc[]:
This method allows you to access rows based on their positions (like row 0, row 1, etc.).
df.iloc[0] # This gives the first row
2. Using .loc[]:
This means that you want to select rows using their index name or row labels, with .loc[].
df.loc[0] # This gives the row with index 0
3. Looping Through Rows:
If you’d like to iterate through each row one at a time, you could use .iterrows().
for index, row in df.iterrows():
print(row)
4. Viewing Top or Bottom Rows:
If you’d like to see just a few rows of the first few or last few, you’d want to use .head() or .tail().
df.head() # Shows the first 5 rows
df.tail() # Shows the last 5 rows
Conclusion
So far in this article, we have learned what is AttributeError: ‘DataFrame’ object has no attribute ‘rows’ and how to fix this. This error arises simply because pandas do not use .rows to index rows in a DataFrame, but rather methods like .iloc[], .loc[], and .iterrows() to access rows. Use them to avoid this error and run your code successfully. If you want to understand similar techniques in SQL, then you should head to our SQL Course right away.