在执行groupby之后删除数据帧的前两行

2024-04-19 20:42:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从数据框df中删除前两行,并使用this post中建议的答案。但是,我得到了错误AttributeError: Cannot access callable attribute 'ix' of 'DataFrameGroupBy' objects, try using the 'apply' method,并且不知道如何使用apply方法来实现这一点。我已经展示了下面的相关代码行:

df = df.groupby('months_to_maturity')
df = df.ix[2:]

编辑:对不起,当我想删除前两行时,我应该说我想删除与每个months_to_maturity值关联的前两行。在

谢谢你


Tags: to数据答案dfaccess错误thispost
1条回答
网友
1楼 · 发布于 2024-04-19 20:42:10

这就是tail(-2)将要做的。但是,groupby.tail不采用负值,因此需要调整:

df.groupby('months_to_maturity').apply(lambda x: x.tail(-2))

这将为您提供所需的数据帧,但它的索引现在是一个多索引。 如果您只想删除df中的行,只需使用drop,如下所示:

^{pr2}$

相关问题 更多 >