我有一個以日期時間為索引的資料框(列中的值無關緊要)。我想在索引等于特定日期 ( 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
uj5u.com熱心網友回復:
你可以試試,
df.index.get_loc(date_to_find)
更快,更易讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355481.html
