如何在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:
- The row itself has a
touvalue ofON_PEAK - The row is the first non-ON_PEAK row immediately following an
ON_PEAKrow
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
相关产品推荐
相关产品推荐

