Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Dataframe rows dynamically

Tags:

python

pandas

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

like image 883
user131983 Avatar asked Jun 25 '26 19:06

user131983


1 Answers

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()
like image 75
alex314159 Avatar answered Jun 27 '26 08:06

alex314159