Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas drop group column after groupby.apply(..)

        uid  iid  val
uid                 
1   1    1    5   5.5
2   3    1    4   3.5
2   2    1    4   3.5
2   7    1    4   3.5
2   9    1    4   3.5
2   11   1    4   3.5

From the dataframe above, I want to remove the first column, which is:

uid
1
2
2
2
2
2

and extract

    uid  iid  val

1    1    5   5.5
3    1    4   3.5
2    1    4   3.5
7    1    4   3.5
9    1    4   3.5
11   1    4   3.5

Can someone help?

like image 338
Mansumen Avatar asked Apr 18 '17 05:04

Mansumen


People also ask

How do I drop index after GroupBy Pandas?

In order to reset the index after groupby() we will use the reset_index() function.

How do I iterate over a group in Pandas?

groupby() to Iterate over Data frame Groups. DataFrame. groupby() function in Python is used to split the data into groups based on some criteria.


2 Answers

You can avoid including the uid in the index in the first place by passing group_keys=False to the groupby

df.groupby('uid', group_keys=False).apply(lambda x: x.tail(len(x) // 5))

   uid  iid  val
4    1    5  5.5
like image 60
piRSquared Avatar answered Oct 08 '22 18:10

piRSquared


Use reset_index or droplevel:

df = df.reset_index(level=0, drop=True)


df = df.reset_index(level='uid', drop=True)

Or:

df.index = df.index.droplevel(0)
like image 44
jezrael Avatar answered Oct 08 '22 17:10

jezrael