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

在R语言中根据两列条件提取对应第三列值到列表

提取DataFrame中满足指定条件的列值到列表

给定的DataFrame

import pandas as pd

df = pd.DataFrame({
    'col1': [1, 0, 2, 1, 2, 0],
    'col2': [2, 1, 2, 2, 0, 1],
    'col3': [2, 0, 1, 1, 0, 2],
    'y': [10, 15, 17, 9, 8, 21]
})

需求说明

提取满足col1 == 0且col2 == 1条件的y列值,组成列表,预期结果为[15, 21]。

解决方案

方法1:布尔索引筛选

通过布尔掩码定位符合条件的行,再提取目标列并转换为列表:

# 筛选符合条件的行
filtered_rows = df[(df['col1'] == 0) & (df['col2'] == 1)]
# 提取y列并转为列表
result_list = filtered_rows['y'].tolist()

print(result_list)  # 输出: [15, 21]

方法2:使用query方法

用字符串表达式简洁筛选数据:

result_list = df.query('col1 == 0 and col2 == 1')['y'].tolist()

print(result_list)  # 输出: [15, 21]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:01:23