为什么不先在一个团队中给我第一个和最后一个 [英] Why doesn't first and last in a groupby give me first and last

查看:89
本文介绍了为什么不先在一个团队中给我第一个和最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



考虑数据框<$ p>

c $ c $ d $


pre $ d $ df = list('xxxyyy'),
B = [np.nan,1,2,3,4,np.nan]
))

AB
0 x NaN
1 x 1.0
2 x 2.0
3 y 3.0
4 y 4.0
5 y NaN

我想得到列'A'定义的每个组的第一行和最后一行。 p>

我试过了

  df.groupby('A')。 agg(['first','last'])

第一个最后
A
x 1.0 2.0 $ b $由3.0 4.0

然而,这并没有给我预期的 np.NaN s。 p>

我如何获得每组中的实际第一个和最后一个值? 一个选择n是使用 .nth 方法:

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

然而,我还没有找到一种方法来整合它们。当然,也可以使用 pd.DataFrame 构造函数:

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

注意:我明确地使用了 gb.B 属性,否则你必须使用 .squeeze


I'm posting this because the topic just got brought up in another question/answer and the behavior isn't very well documented.

Consider the dataframe df

df = pd.DataFrame(dict(
    A=list('xxxyyy'),
    B=[np.nan, 1, 2, 3, 4, np.nan]
))

   A    B
0  x  NaN
1  x  1.0
2  x  2.0
3  y  3.0
4  y  4.0
5  y  NaN

I wanted to get the first and last rows of each group defined by column 'A'.

I tried

df.groupby('A').B.agg(['first', 'last'])

   first  last
A             
x    1.0   2.0
y    3.0   4.0

However, This doesn't give me the np.NaNs that I expected.

How do I get the actual first and last values in each group?

解决方案

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

这篇关于为什么不先在一个团队中给我第一个和最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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