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

pandas如何获取指定列范围内满足条件的行位置(np.where返回空)

问题根因

你现有代码跑不出预期结果有3个明确问题:

  • 你贴的代码里df是原生Python字典,不是pandas DataFrame,不存在.iloc属性,正常运行会直接抛出AttributeError,能返回空数组说明你实际运行的代码和贴出的版本不一致。
  • pandas的.iloc切片遵循Python左闭右开规则,你写的iloc[first:last]只会取到索引为last-1=17的行,你需要的索引18的行根本不在切片范围内。
  • 就算切片范围正确,np.where在切片后的子Series上返回的是子序列内部的相对位置(从0开始计数),不会自动映射回原始DataFrame的全局行位置。
可运行修正代码

完全可以通过np.where+iloc的组合实现需求,只需要修正上述三个问题即可:

import pandas as pd
import numpy as np

# 正确初始化DataFrame
df = pd.DataFrame({
    'Stress': [1,2,3,6,7,8,10,12,14,20,19,17,15,13,12,10,8,7,6,4,1,0]
})

first = 10
last = 18
drop = 11

# iloc左闭右开,要包含last位置的行,切片上界需要设为last+1
sub_stress = df['Stress'].iloc[first : last + 1]
# 拿到子序列相对位置后,加first偏移量得到原始全局行索引
life_array = np.where(sub_stress < drop)[0] + first

执行后life_array的值就是[15 16 17 18],完全符合你的预期。

如果你需要示例里带行序号的输出格式,直接将结果转为Series打印即可:

print(pd.Series(life_array))

输出结果:

0    15
1    16
2    17
3    18
dtype: int64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:45:25