Fix Python – Extract first and last row of a dataframe in pandas

Question

Asked By – Bryan P

How can I extract the first and last rows of a given dataframe as a new dataframe in pandas?

I’ve tried to use iloc to select the desired rows and then concat as in:

df=pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
pd.concat([df.iloc[0,:], df.iloc[-1,:]])

but this does not produce a pandas dataframe:

a    1
b    a
a    4
b    d
dtype: object

Now we will see solution for issue: Extract first and last row of a dataframe in pandas


Answer

I think the most simple way is .iloc[[0, -1]].

df = pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
df2 = df.iloc[[0, -1]]
    
print(df2)

   a  b
0  1  a
3  4  d

This question is answered By – su79eu7k

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0