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

Pandas中如何结合索引与列值条件筛选DataFrame行

Pandas 复合筛选实现方法

你可以通过两种思路实现需求,既可以直接构造复合布尔条件一次性筛选,也可以拆分iloc、loc的筛选逻辑后合并结果:

方法1:布尔索引一次性筛选(鲁棒性最优)

不需要拆分iloc和loc的逻辑,直接构造覆盖三个保留规则的布尔序列即可,即使原DataFrame索引不是默认连续整数也不会出错:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'value_1': [1,9,2,7,2],
    'value_2': [2,6,5,2,5]
})

# 筛选条件:是首行 | 是末行 | value_1大于3
filter_cond = (df.index == df.index[0]) | (df.index == df.index[-1]) | (df['value_1'] > 3)
result = df[filter_cond]

方法2:拼接iloc、loc的筛选结果(贴合用法结合需求)

分别用iloc取首尾行、用loc取列值符合条件的行,再拼接去重即可,逻辑拆分更直观:

result = pd.concat([
    df.iloc[[0]],          # iloc取首行,传列表保证返回DataFrame格式
    df.loc[df['value_1'] > 3],  # loc按列值筛选
    df.iloc[[-1]]          # iloc取末行
]).drop_duplicates()       # 去重避免首尾行刚好满足值条件时出现重复

两种方法运行后得到的结果完全匹配预期:

value_1  value_2
0        1        2
1        9        6
3        7        2
4        2        5

注意:用iloc取单行时要传入包裹索引的列表(比如[0]而不是直接传0),否则返回的是Series格式,拼接时会出现结构错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 12:27:44