You need to enable JavaScript to run this app. Python DataFrame按C列值打印对应行及下一行内容的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Python DataFrame按C列值打印对应行及下一行内容的实现方法

问题解决方法

报错原因

你写的if (df['c'] == 1)会返回一整列布尔值的Series,Python原生的if判断无法直接判定一整组布尔值的真假,所以抛出了这个歧义错误。

实现代码

核心逻辑是先筛选出所有C列等于1的行的索引,再遍历这些索引依次配对当前行和后一行即可,完整示例如下:

import pandas as pd

# 替换为你自己的DataFrame
df = pd.DataFrame({
    'A': ['test1', 'test2', 'test3', 'test4', 'test5'],
    'B': [10, 20, 30, 40, 50],
    'C': [1, 0, 1, 1, 0]
})

# 取出所有C列为1的行的索引
c1_index_list = df[df['C'] == 1].index
seq_num = 1

for idx in c1_index_list:
    # 避免最后一行索引越界
    if idx >= len(df) - 1:
        continue
    # 可根据需求自定义行内容的拼接规则,以下为全列拼接示例
    current_row = ','.join(df.loc[idx].astype(str).to_list())
    next_row = ','.join(df.loc[idx + 1].astype(str).to_list())
    print(f"{seq_num}. {current_row}; {next_row}")
    seq_num += 1

输出示例

以上面的测试DataFrame为例,输出结果如下:

1. test1,10,1; test2,20,0
2. test3,30,1; test4,40,1
3. test4,40,1; test5,50,0

如果只需要输出指定列的内容,调整current_row和next_row的拼接逻辑即可,比如只取A、B两列:

current_row = f"A={df.loc[idx, 'A']},B={df.loc[idx, 'B']}"
next_row = f"A={df.loc[idx+1, 'A']},B={df.loc[idx+1, 'B']}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:27:03