Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas get number of row for specific date with time as index

I have a dataframe with datetime as index (the values in columns don’t matter). I would like to extract the row number when the index is equal to a specific date (2021/06/25 16:00:00). How can I do that ? The only way I found was to add a count column and use loc, but I wondered if there was a better way to do it.

import pandas as pd
from datetime import date, datetime, timedelta

sdate = datetime(2021,6,5,14)  # Start date
edate = datetime(2021,6,30)   # End Date
date_to_find = datetime(2021,6,25,16)
df = pd.DataFrame(index=pd.date_range(sdate, edate, freq='H'))   # Create a dataframe with date as index, every hour

df.insert(0, 'row_num', range(0,len(df)))  # here you insert the row count
df.loc[df.index == date_to_find]['row_num'][0]  # Grab the row number for which the index equals the date to find

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can try with,

df.index.get_loc(date_to_find)

is faster and more readable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading