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

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:

Creating "hitlast" and "misslast" Columns in Pandas

First, let's break down the logic we need to implement:

  • hitlast: Should be True only when the current row's response is True AND the next row's Confidence is True; otherwise False.
  • misslast: Should be True only when the current row's response is False AND the next row's Confidence is False; otherwise False.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:26:39