You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中获取符合状态切换条件的索引?

Solution to the Two Pandas Index Retrieval Tasks

First, let's confirm we're working with the same sample DataFrame as provided:

import pandas as pd

index = pd.date_range(start='1/1/2018', periods=6, freq='15T')
data = ['ON_PEAK', 'OFF_PEAK', 'ON_PEAK', 'ON_PEAK', 'OFF_PEAK', 'OFF_PEAK']
df = pd.DataFrame(data, index=index, columns=['tou'])

Task 1: Get indices where current row is non-ON_PEAK and previous row is ON_PEAK

We use Pandas' shift() method to compare each row with its predecessor. The condition checks if the current tou value isn't ON_PEAK, but the row immediately before it was. We then extract the matching indices and format them as strings:

# Define the condition for the desired rows
condition = (df['tou'] != 'ON_PEAK') & (df['tou'].shift(1) == 'ON_PEAK')

# Extract and format the indices
result1 = df[condition].index.strftime('%Y-%m-%d %H:%M:%S').tolist()

print(result1)
# Output: ['2018-01-01 00:15:00', '2018-01-01 01:00:00']

Task 2: Get all ON_PEAK row indices plus the first row after each ON_PEAK segment

We create a boolean mask that covers two scenarios:

  1. The row itself has a tou value of ON_PEAK
  2. The row is the first non-ON_PEAK row immediately following an ON_PEAK row

Applying this mask to the DataFrame gives us the target rows, then we extract and format their indices:

# Create the mask for ON_PEAK rows and the first row after each ON_PEAK block
mask = (df['tou'] == 'ON_PEAK') | ((df['tou'].shift(1) == 'ON_PEAK') & (df['tou'] != 'ON_PEAK'))

# Extract and format the indices
result2 = df[mask].index.strftime('%Y-%m-%d %H:%M:%S').tolist()

print(result2)
# Output: ['2018-01-01 00:00:00', '2018-01-01 00:15:00', '2018-01-01 00:30:00', '2018-01-01 00:45:00', '2018-01-01 01:00:00']

内容的提问来源于stack exchange,提问作者DEEPAK SURANA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:40:45