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

PySpark中如何基于列值过滤Row列表并获取指定字段值

过滤Row列表并获取目标num_samples值

方法1:列表推导式(简洁高效)

直接用列表推导式筛选出sample_label等于0的Row,再提取对应的num_samples:

rows = [Row(sample_label=1, num_samples=14398),
        Row(sample_label=0, num_samples=12500),
        Row(sample_label=2, num_samples=98230)]

# 直接提取(假设一定存在匹配项)
target_num = [row.num_samples for row in rows if row.sample_label == 0][0]
print(target_num)  # 输出 12500

如果怕没有匹配项报错,可以先做判断:

target_list = [row.num_samples for row in rows if row.sample_label == 0]
target_num = target_list[0] if target_list else None  # 无匹配时返回None,按需调整

方法2:filter函数配合lambda

用filter()快速筛选符合条件的Row,再取值:

from pyspark.sql import Row

rows = [Row(sample_label=1, num_samples=14398),
        Row(sample_label=0, num_samples=12500),
        Row(sample_label=2, num_samples=98230)]

# 筛选后转列表取第一个,再提取num_samples
filtered_row = list(filter(lambda x: x.sample_label == 0, rows))[0]
target_num = filtered_row.num_samples
print(target_num)  # 输出 12500

方法3:循环遍历(直观易懂)

逐个遍历Row,检查sample_label,符合条件就提取值:

rows = [Row(sample_label=1, num_samples=14398),
        Row(sample_label=0, num_samples=12500),
        Row(sample_label=2, num_samples=98230)]

target_num = None
for row in rows:
    if row.sample_label == 0:
        target_num = row.num_samples
        break  # 找到就退出循环,不用继续遍历

print(target_num)  # 输出 12500

补充说明:Row对象支持两种属性访问方式,除了row.sample_label,也可以用字典式访问row['sample_label'],效果完全一致,选你习惯的方式就行。

内容的提问来源于stack exchange,提问作者Salty Gold Fish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:45:30