Pandas 获取以时间为索引的特定日期的行数
Pandas get number of row for specific date with time as index
我有一个以日期时间为索引的数据框(列中的值无关紧要)。我想在索引等于特定日期(2021/06/25 16:00:00
)时提取行号。我怎样才能做到这一点 ?我找到的唯一方法是添加一个计数列并使用 loc
,但我想知道是否有更好的方法。
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
你可以试试,
df.index.get_loc(date_to_find)
更快,更易读。
我有一个以日期时间为索引的数据框(列中的值无关紧要)。我想在索引等于特定日期(2021/06/25 16:00:00
)时提取行号。我怎样才能做到这一点 ?我找到的唯一方法是添加一个计数列并使用 loc
,但我想知道是否有更好的方法。
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
你可以试试,
df.index.get_loc(date_to_find)
更快,更易读。