Retrieve elements from the head and tail of a pandas DataFrame
The head() method selects first 'n' elements from a DataFrame instance. Similarly, the tail() method of the DataFrame class selects the last 'n' number of rows.
The first ‘n’ rows of a DataFrame can be selected using the instance method head(). The parameter ‘n’ specifies the number of rows to be present in the returned DataFrame.
Similarly, the tail() method of the DataFrame returns the last ‘n’ rows of a DataFrame as a separate DataFrame instance.
The default value for parameter 'n' in both the head() and tail() method is 5.
Example – Retrieve first ‘n’ rows of a DataFrame using head() method
python
# Example Python program that selects first 'n' rows of a DataFrame
# using the instance method head()
import pandas as pds
numRows2Select = 2;
# List of tuples
colorData = [("red", "blue", "green"),
("white", "grey", "black"),
("cyan", "purple", "brown")];
# Create a dataframe from a list of tuples
dataFrame = pds.DataFrame(colorData);
# Select first two rows of a DataFrame
firstFive = dataFrame.head(numRows2Select);
# Print the new DataFrame
print("First %d rows of a DataFrame selected using head():"%numRows2Select);
print(firstFive);
print(type(firstFive));
Output
Output
First 2 rows of a DataFrame selected using head():
0 1 2
0 red blue green
1 white grey black
<class 'pandas.core.frame.DataFrame'>
Example – Retrieve last ‘n’ rows of a DataFrame using tail() method
python
# Example Python program that selects last 'n' rows
# from a pandas DataFrame instance
import pandas as pds
# A list of tuples representing flight routes
routes = [("Dallas, Frankfurt, Singapore"),
("New York, London, Singapore"),
("Chicago, London, Bangkok"),
("San Francisco, Paris, Hong Kong"),
("Phoenix, Amsterdam, Seoul")];
# Create a DataFrame object
df = pds.DataFrame(routes, index=["R1", "R2", "R3", "R4", "R5"], columns=["Cities"]);
# Print the contents
print("The contents of the DataFrame:");
print(df);
# Print only the last two rows
print("Last 2 rows of the DataFrame selected using DataFrame.tail():");
print(df.tail(2));
Output
Output
The contents of the DataFrame:
Cities
R1 Dallas, Frankfurt, Singapore
R2 New York, London, Singapore
R3 Chicago, London, Bangkok
R4 San Francisco, Paris, Hong Kong
R5 Phoenix, Amsterdam, Seoul
Last 2 rows of the DataFrame selected using DataFrame.tail():
Cities
R4 San Francisco, Paris, Hong Kong
R5 Phoenix, Amsterdam, Seoul
Your privacy choices
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on