如何在Pandas中按每日06:00~08:00时间范围筛选多重索引数据?
Hey there! Let's figure out how to filter your MultiIndex DataFrame to only keep rows between 6:00 and 8:00 every day. I've got two solid approaches for you:
方法1:直接针对Time层级的索引筛选
Since your DataFrame uses Date and Time as a MultiIndex, we can directly target the Time level to filter our desired range. This keeps your original index structure intact:
import pandas as pd # Optional: If your 'Time' index is stored as strings, convert it to datetime.time type first for safer comparisons time_level = pd.to_datetime(df.index.get_level_values('Time')).time df.index = df.index.set_levels(time_level, level='Time') # Define our target time range start = pd.to_datetime('06:00:00').time() end = pd.to_datetime('08:00:00').time() # Filter the DataFrame filtered_df = df[(df.index.get_level_values('Time') >= start) & (df.index.get_level_values('Time') <= end)]
If your Time values are already in datetime.time format, you can skip the conversion step and jump straight to filtering.
方法2:合并索引为Datetime后使用between_time
If you prefer a more intuitive approach (and might need to do more time-based operations later), merging the Date and Time levels into a single datetime index makes things super easy with pandas' built-in between_time method:
import pandas as pd # Combine Date and Time into a single datetime column df['full_datetime'] = pd.to_datetime( df.index.get_level_values('Date').astype(str) + ' ' + df.index.get_level_values('Time').astype(str) ) # Set this new column as the index df = df.set_index('full_datetime') # Filter rows between 6:00 and 8:00 daily filtered_df = df.between_time('06:00', '08:00') # Optional: Restore the original MultiIndex if needed filtered_df['Date'] = filtered_df.index.date filtered_df['Time'] = filtered_df.index.time filtered_df = filtered_df.set_index(['Date', 'Time'])
Quick Notes
- If your
Timevalues are strings like5:15:00(without leading zeros), converting todatetime.timeis still safe—pandas handles that automatically. - The first method is great if you want to keep your original index structure without modifications. The second method is more flexible for future time-based analysis.
内容的提问来源于stack exchange,提问作者jerry han

