Pandas:基于列值与下一行列值的逻辑比较问题
Got it, let's figure out how to create those two columns for your Pandas DataFrame! Here's a straightforward approach based on your requirements:
First, let's break down the logic we need to implement:
- hitlast: Should be
Trueonly when the current row'sresponseisTrueAND the next row'sConfidenceisTrue; otherwiseFalse. - misslast: Should be
Trueonly when the current row'sresponseisFalseAND the next row'sConfidenceisFalse; otherwiseFalse.
The core tool here is Pandas' shift() method, which lets us access values from adjacent rows easily. Here's how to put it all together:
Step 1: Example DataFrame (for context)
Let's start with a sample DataFrame to demonstrate the workflow:
import pandas as pd # Sample boolean data matching your column names data = { 'response': [True, False, True, False, True], 'Confidence': [False, True, True, False, True] } df = pd.DataFrame(data)
Step 2: Generate the new columns
We'll first create a series that holds the next row's Confidence value using shift(-1), then combine it with the current row's response values using boolean logic:
# Get the Confidence value from the next row next_confidence = df['Confidence'].shift(-1) # Create hitlast: current response is True AND next Confidence is True df['hitlast'] = df['response'] & next_confidence # Create misslast: current response is False AND next Confidence is False df['misslast'] = (~df['response']) & (~next_confidence)
Step 3: Check the result
After running the code, your DataFrame will look like this:
response Confidence hitlast misslast 0 True False True False 1 False True False False 2 True True False False 3 False False False True 4 True True False False
Note that the last row's hitlast and misslast are False automatically—since there's no next row to compare with, shift(-1) returns NaN for the final row, and boolean comparisons with NaN evaluate to False.
Quick Simplification Tip
Since your response and Confidence columns are already boolean, you don't need to explicitly compare to True/False—the code above uses direct boolean operations (& for AND, ~ for NOT) which is cleaner and more efficient.
内容的提问来源于stack exchange,提问作者Antonella Marabotto

