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

如何获取DataFrame中A_column列值为Apple的行索引?

获取DataFrame中指定列值的行索引

嘿,这事儿不难,我给你分享几个实用的方法来获取A_column列值为Apple的所有行索引:

  • 方法一:布尔索引 + .index
    这是最直观的方式,先通过布尔条件筛选出目标行,再提取索引并转成列表:

    # 筛选A_column为Apple的行,获取索引后转成列表
    apple_indices = df[df['A_column'] == 'Apple'].index.tolist()
    print(apple_indices)  # 输出: [0, 3, 4]
    
  • 方法二:使用query()函数
    如果你的筛选条件比较简单,用query()会更简洁:

    # 通过query筛选目标行,提取索引转列表
    apple_indices = df.query("A_column == 'Apple'").index.tolist()
    
  • 方法三:借助numpy.where()
    如果你习惯用numpy的工具,也可以用np.where()直接定位符合条件的索引位置:

    import numpy as np
    
    # np.where返回满足条件的索引数组,转成列表
    apple_indices = np.where(df['A_column'] == 'Apple')[0].tolist()
    

这几种方法都能得到你想要的[0,3,4]结果,你可以根据自己的习惯选着用~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:53:47