Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

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

1 Answer

0 votes
by (107k points)

The most simple way is .iloc[[0, -1]]. Refer to the following code:

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

If you wish to learn more about Pandas visit this Pandas Tutorial.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...