如何在含65200行的DataFrame中查找sma1的5和sma2的90的索引?
获取DataFrame中指定列特定值的索引位置
精确匹配场景
假设你的DataFrame名为df,可通过布尔索引筛选目标值对应的行,再提取索引:
- 获取
sma1列中数值为5的索引:df[df['sma1'] == 5].index - 获取
sma2列中数值为90的索引:df[df['sma2'] == 90].index
浮点数精度兼容场景
如果sma1/sma2是浮点数类型,直接用==可能因精度问题匹配失败,建议用numpy的isclose方法设置误差范围:
- 先导入numpy:
import numpy as np - 匹配并提取索引:
- 匹配
sma1列中接近5的值:df[np.isclose(df['sma1'], 5, atol=1e-6)].index - 匹配
sma2列中接近90的值:df[np.isclose(df['sma2'], 90, atol=1e-6)].index
- 匹配
转换为列表(可选)
若需将索引转为普通Python列表,在末尾追加.tolist()即可,例如:
df[df['sma1'] == 5].index.tolist()
内容的提问来源于stack exchange,提问作者Ali Farhan
相关产品推荐
相关产品推荐

