Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first and last row of a dataframe in pandas

Tags:

python

pandas

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 
like image 628
Bryan P Avatar asked Apr 11 '16 07:04

Bryan P


People also ask

How do I get the last row of a pandas Dataframe?

Select & print last row of dataframe using tail() It will return the last row of dataframe as a dataframe object. Using the tail() function, we fetched the last row of dataframe as a dataframe and then just printed it.

How will you get the top 2 rows from a Dataframe in pandas?

pandas.DataFrame.head() In Python's Pandas module, the Dataframe class provides a head() function to fetch top rows from a Dataframe i.e. It returns the first n rows from a dataframe.


1 Answers

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 
like image 164
su79eu7k Avatar answered Sep 21 '22 07:09

su79eu7k