3

I have a column called maturity_dt filled with datetime objects in my dataframe df, and I am just trying to select only the rows in the column which have a maturity_dt in August or February. So, I am trying to delete all the rows that do not correspond with these months dynamically using the code below. However, I get the error IndexError: index 109235 is out of bounds for axis 0 with size 44681 despite using reset_index, so I am wondering if there is another way to delete rows dynamically.

for (i, row) in df.iterrows():
        dateold = datetime.datetime.strptime(row['maturity_dt'], '%Y-%m-%d %H:%M:%S.%f')
        datenew = dateold.date()
        date = str(datenew).split('.')[0]
        h,m,s = re.split('-', date)
        if m != 2 and m != 8:  # If the month is not Feb or August
            df.drop(df.index[i])
            df = df.reset_index(drop=True)

Thank You

firelynx
  • 30,616
  • 9
  • 91
  • 101
user131983
  • 3,787
  • 4
  • 27
  • 42

1 Answers1

2

Can you reindex by date? This would work:

df['dt']=pandas.Datetimeindex(df['maturity_dt'])
df=df.set_index('dt')
df=df.loc[(df.index.month==2) | (df.index.month==8)].copy()
alex314159
  • 3,159
  • 2
  • 20
  • 28
  • Unfortunately this results in the error `AttributeError: 'Series' object has no attribute 'month'`. – user131983 Jul 13 '15 at 20:46
  • should be sorted now - apparently you can only call .month on the index – alex314159 Jul 13 '15 at 20:52
  • Thanks. But, now the error is `AttributeError: 'Index' object has no attribute 'month'` – user131983 Jul 13 '15 at 20:59
  • Strange, it works for me on dummy table - try forcing a Datetimeindex as per above – alex314159 Jul 13 '15 at 21:34
  • @ alex314159 Are you using `date` Objects instead of `datetime` Objects possibly for `df['maturity_dt']`? – user131983 Jul 13 '15 at 21:37
  • @user131983 datetime. Is it a version issue? This suggests it has to be 0.15 or above [http://stackoverflow.com/questions/21954197/which-is-the-fastest-way-to-extract-day-month-and-year-from-a-given-date] – alex314159 Jul 13 '15 at 21:48