从每个组中放下第一行和最后一行 [英] drop first and last row from within each group

查看:113
本文介绍了从每个组中放下第一行和最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是


This is a follow up question to get first and last values in a groupby

How do I drop first and last rows within each group?

I have this df

df = pd.DataFrame(np.arange(20).reshape(10, -1),
                  [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
                   ['a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
                  ['X', 'Y'])

df

I intentionally made the second row have the same index value as the first row. I won't have control over the uniqueness of the index.

      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 b   2.0   3
  c   4.0   5
b f  10.0  11

Because both groups at level 0 equal to 'c' and 'd' have less than 3 rows, all rows should be dropped.

解决方案

I'd apply a similar technique to what I did for the other question:

def first_last(df):
    return df.ix[1:-1]

df.groupby(level=0, group_keys=False).apply(first_last)

这篇关于从每个组中放下第一行和最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆