gpt4 book ai didi

python - Groupby - 取最后一个元素 - 我如何保留 nan 的?

转载 作者:太空狗 更新时间:2023-10-30 00:07:21 28 4
gpt4 key购买 nike

我有一个 df,我想通过 CUSIP 获取下面的最新行。

In [374]: df.head()
Out[374]:
CUSIP COLA COLB COLC
date
1992-05-08 AAA 238 4256 3.523346
1992-07-13 AAA NaN 4677 3.485577
1992-12-12 BBB 221 5150 3.24
1995-12-12 BBB 254 5150 3.25
1997-12-12 BBB 245 Nan 3.25
1998-12-12 CCC 234 5140 3.24145
1999-12-12 CCC 223 5120 3.65145

我正在使用:

df = df.reset_index().groupby('CUSIP').last().reset_index.set_index('date')

我想要这个:

              CUSIP        COLA         COLB       COLC  
date
1992-07-13 AAA NaN 4677 3.485577
1997-12-12 BBB 245 Nan 3.25
1999-12-12 CCC 223 5120 3.65145

相反,我得到:

              CUSIP        COLA         COLB       COLC  
date
1992-07-13 AAA 238 4677 3.485577
1997-12-12 BBB 245 5150 3.25
1999-12-12 CCC 223 5120 3.65145

如何让 last() 获取 groupby 的最后一行,包括 NaN?

谢谢。

最佳答案

您可以直接使用 apply 而不是 last 执行此操作(并获取每个组的第 -1 行):

In [11]: df.reset_index().groupby('CUSIP').apply(lambda x: x.iloc[-1]).reset_index(drop=True).set_index('date')
Out[11]:
CUSIP COLA COLB COLC
date
1992-07-13 AAA NaN 4677 3.485577
1997-12-12 BBB 245 NaN 3.250000
1999-12-12 CCC 223 5120 3.651450

[3 rows x 4 columns]

在 0.13(现在 rc 出来了)中,一个更快更直接的方法是使用 cumcount :

In [12]: df[df.groupby('CUSIP').cumcount(ascending=False) == 0]
Out[12]:
CUSIP COLA COLB COLC
date
1992-07-13 AAA NaN 4677 3.485577
1997-12-12 BBB 245 NaN 3.250000
1999-12-12 CCC 223 5120 3.651450

[3 rows x 4 columns]

关于python - Groupby - 取最后一个元素 - 我如何保留 nan 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643765/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com