基于列条件查找目标列值:Pandas获取首个指定值对应ts
在Pandas中基于列条件查找对应列的首个匹配值
需求:在给定的Pandas DataFrame中,查找value列里首个'B'对应的ts列值,期望输出结果为30。
示例数据及初始化代码:
import pandas as pd data = [[10,"A"],[20,"A"],[30,"B"],[40,"B"]] df = pd.DataFrame(data,columns=['ts','value']) print(df) # 输出结果 # ts value # 0 10 A # 1 20 A # 2 30 B # 3 40 B
几种实现方法
- 布尔索引+iloc提取首个值
# 筛选value为'B'的行,提取ts列并取第一个元素 result = df[df['value'] == 'B']['ts'].iloc[0] print(result) # 输出:30
原理:通过df['value'] == 'B'生成布尔筛选条件,过滤出符合要求的行后,直接提取ts列,用iloc[0]定位第一个匹配结果。
- 利用idxmax获取首个匹配索引
# 找到首个value为'B'的行索引,再提取对应ts值 match_idx = (df['value'] == 'B').idxmax() result = df.loc[match_idx, 'ts'] print(result) # 输出:30
原理:布尔序列中True等价于1、False等价于0,idxmax()会返回第一个值为1的索引位置,再通过loc索引提取对应ts值。
- 使用query方法筛选
# 通过字符串表达式筛选行,提取首个ts值 result = df.query("value == 'B'")['ts'].iloc[0] print(result) # 输出:30
原理:query()支持用类SQL的字符串语法筛选数据,后续操作和第一种方法一致。
内容的提问来源于stack exchange,提问作者lucky1928
相关产品推荐
相关产品推荐

