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

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

6 Comments

Unfortunately this results in the error AttributeError: 'Series' object has no attribute 'month'.
should be sorted now - apparently you can only call .month on the index
Thanks. But, now the error is AttributeError: 'Index' object has no attribute 'month'
Strange, it works for me on dummy table - try forcing a Datetimeindex as per above
@ alex314159 Are you using date Objects instead of datetime Objects possibly for df['maturity_dt']?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.