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

Time:11-10

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

CodePudding user response:

You can try with,

df.index.get_loc(date_to_find)

is faster and more readable.

  • Related