1

Follow up question from here: drop first and last row from within each group

In pandas, how do you drop the last row in the first groupby then the first row for all subsequent entries in the group?

e.g

      X   Y
a a   0   1
  a   2   3
  c   4   5
  d   6   7
b e   8   9
  f  10  11
  g  12  13
c h  14  15
  i  16  17
d j  18  19

I want this

    X   Y
a d 6   7
b e 8   9
c h 14 15
d j 18 19
dmin
  • 78
  • 7

1 Answers1

3

First check first value of first level by get_level_values and then groupby with apply - first group by tail and all another by head:

first = df.index.get_level_values(0)[0]
df = df.groupby(level=0, sort=False, group_keys=False)
       .apply(lambda x: x.tail(1) if x.name == first else x.head(1))
print (df)
      X   Y
a d   6   7
b e   8   9
c h  14  15
d j  18  19
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252