Why doesn't first and last in a groupby give me first and last

試著忘記壹切 提交于 2019-11-29 10:48:51

One option is to use the .nth method:

>>> gb = df.groupby('A')
>>> gb.nth(0)
     B
A
x  NaN
y  3.0
>>> gb.nth(-1)
     B
A
x  2.0
y  NaN
>>>

However, I haven't found a way to aggregate them neatly. Of course, one can always use a pd.DataFrame constructor:

>>> pd.DataFrame({'first':gb.B.nth(0), 'last':gb.B.nth(-1)})
   first  last
A
x    NaN   2.0
y    3.0   NaN

Note: I explicitly used the gb.B attribute, or else you have to use .squeeze

As noted here by @unutbu:

The groupby.first and groupby.last methods return the first and last non-null values respectively.

To get the actual first and last values, do:

def h(x):
    return x.values[0]

def t(x):
    return x.values[-1]

df.groupby('A').B.agg([h, t])

     h    t
A          
x  NaN  2.0
y  3.0  NaN
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!