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

jezrael's answer is perfect. Just to provide an alternative, if you insist on using loc then you should first reset_index.

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 df['index'].iloc[0]
print df['index'].iloc[-1]

You can use select index by [0] or [-1]:

df = pd.DataFrame({'myfield':[1,4,5]}, index=pd.date_range('2015-01-01', periods=3))
print (df)
            myfield
2015-01-01        1
2015-01-02        4
2015-01-03        5

print (df.iloc[-1])
myfield    5
Name: 2015-01-03 00:00:00, dtype: int64

print (df.index[0])
2015-01-01 00:00:00

print (df.index[-1])
2015-01-03 00:00:00

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())