Python: How to get the values of the first and last rows of a specific column in a pandas dataframe

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

This is a memo on how to get the values of the first and last rows of a specific column in a dataframe using Python and pandas.
You can use them in the same way, but I think that head or tail is often used to visually check the data content, and iloc is used to get the data range.

import pandas as pd

df = pd.DataFrame([
["1","05/22/2020","A"],
["2","05/23/2020","B"],
["3","05/24/2020","C"]],
columns=['id', 'date', 'something'])

# head or tail
print(df['date'].head(1).item()) # 05/22/2020
print(df['date'].tail(1).item()) # 05/24/2020

# iloc
print(df['date'].iloc[0]) # 05/22/2020
print(df['date'].iloc[-1]) # 05/24/2020
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.