Pandas Dataframe/Series.tail() method
0 690
Exploring the Pandas tail() Method
The tail() method in Pandas is a convenient function that allows you to quickly preview the last few rows of a DataFrame or Series. By default, it returns the last 5 rows, but you can specify a different number to suit your needs. This method is invaluable when you're working with large datasets and want to get a quick glimpse of the data structure without loading the entire dataset into memory.
Syntax
DataFrame.tail(n=5)
Parameters:
n: int, default 5 — The number of rows to return. If not specified, it returns the last 5 rows.
Returns:
DataFrame— A DataFrame containing the lastnrows.
Example Usage
import pandas as pd
# Sample DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace'],
'Age': [25, 30, 35, 40, 22, 29, 31],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio']
}
df = pd.DataFrame(data)
# Display the last 5 rows
print(df.tail())
# Display the last 3 rows
print(df.tail(3))
Output:
Name Age City
2 Charlie 35 Chicago
3 David 40 Houston
4 Eva 22 Phoenix
5 Frank 29 Philadelphia
6 Grace 31 San Antonio
Using tail() with Series
The tail() method can also be applied to a Pandas Series to view the last few elements:
# Sample Series
ages = pd.Series([25, 30, 35, 40, 22, 29, 31])
# Display the last 5 elements
print(ages.tail())
# Display the last 3 elements
print(ages.tail(3))
Output:
2 35
3 40
4 22
5 29
6 31
dtype: int64
Practical Applications
- Quick Data Inspection: Use
tail()to quickly inspect the last few rows of your dataset to understand its structure. - Data Cleaning: Before performing data cleaning operations, it's useful to check the final rows to identify any obvious issues.
- Debugging: When writing data processing code,
tail()can help you verify that your transformations are working as expected on a small subset of the data.
Conclusion
The tail() method is a simple yet powerful tool in the Pandas library that aids in quickly previewing the last few rows of a DataFrame or Series. It's especially useful when dealing with large datasets, allowing you to get a sense of the data without having to load the entire dataset into memory. By mastering this method, you lay the groundwork for more complex data manipulations and analyses using Pandas.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments