1

I am trying to delete the first two rows from my dataframe df and am using the answer suggested in this post. However, I get the error AttributeError: Cannot access callable attribute 'ix' of 'DataFrameGroupBy' objects, try using the 'apply' method and don't know how to do this with the apply method. I've shown the relevant lines of code below:

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

Edit: Sorry, when I mean I want to delete the first two rows, I should have said I want to delete the first two rows associated with each months_to_maturity value.

Thank You

Community
  • 1
  • 1
user131983
  • 3,787
  • 4
  • 27
  • 42
  • You mean you want to ignore the first two groups? What manner of aggregation were you planning on doing to those groups? note that you are redefining `df` each line. – mdurant Jul 29 '15 at 13:45
  • The groupby object essentially just holds metadata about how to perform the groupby so what you are trying won't work. What do you mean by first 2 rows? You could do `df = df.groupby('months_to_maturity', as_index=False)` which will allow you to remove the first 2 rows on your next line – EdChum Jul 29 '15 at 13:48
  • @EdChum I apologize. I've added more info to the question. – user131983 Jul 29 '15 at 13:54
  • So does `df = df.groupby('months_to_maturity', as_index=False) df = df.ix[2:]` work? – EdChum Jul 29 '15 at 13:59
  • @EdChum I get the same error as before unfortunately. – user131983 Jul 29 '15 at 15:24

1 Answers1

0

That is what tail(-2) will do. However, groupby.tail does not take a negative value, so it needs a tweak:

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

This will give you desired dataframe but its index is a multi-index now. If you just want to drop the rows in df, just use drop like this:

df.drop(df.groupby('months_to_maturity').head(2).index)
Jihun
  • 1,415
  • 1
  • 12
  • 16