Pandas: How do I get the key (index) of the first and last row of a dataframe

Viewed 34046

I have a dataframe (df) with a datetime index and one field "myfield"

I want to find out the first and last datetime of the dataframe.

I can access the first and last dataframe element like this:

df.iloc[0]
df.iloc[-1]

for df.iloc[0] I get the result:

myfield myfieldcontent

Name: 2017-07-24 00:00:00, dtype: float

How can I access the datetime of the row?

3 Answers

If you are using pandas 1.1.4 or higher, you can use "name" attribute.

import pandas as pd

df = pd.DataFrame({'myfield': [1, 4, 5]}, index=pd.date_range('2015-01-01', periods=3))
df = df.reset_index()
print("Index value: ", df.iloc[-1].name) #pandas-series
#Convert to python datetime
print("Index datetime: ", df.iloc[-1].name.to_pydatetime()) 
Related