【问题标题】:Deleting first two rows of a dataframe after doing groupby执行 groupby 后删除数据帧的前两行
【发布时间】:2015-10-20 12:58:23
【问题描述】:

我正在尝试从我的数据框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 值关联的前两行。

谢谢

【问题讨论】:

  • 您的意思是要忽略前两组?您打算对这些群体采取何种聚合方式?请注意,您正在重新定义 df 每一行。
  • groupby 对象本质上只是保存有关如何执行 groupby 的元数据,因此您尝试的操作将不起作用。前两行是什么意思?您可以执行df = df.groupby('months_to_maturity', as_index=False),这将允许您删除下一行的前 2 行
  • @EdChum 我很抱歉。我已在问题中添加了更多信息。
  • df = df.groupby('months_to_maturity', as_index=False) df = df.ix[2:] 工作吗?
  • @EdChum 不幸的是,我得到了和以前一样的错误。

标签: python pandas


【解决方案1】:

这就是tail(-2) 会做的事情。但是,groupby.tail 不带负值,因此需要调整:

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

这将为您提供所需的数据框,但它的索引现在是多索引。 如果您只想删除df 中的行,只需像这样使用drop

df.drop(df.groupby('months_to_maturity').head(2).index)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2021-11-06
    相关资源
    最近更新 更多