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

基于多列值筛选Pandas DataFrame行的实现困惑与需求

实现方法:保留所有行,仅指定列保留目标值

先假设我们有这样的示例DataFrame:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['one', 'two', 'three', 'two', 'five']})

你的需求是保留A列的所有行(也就是整个DataFrame的行数不变),但只保留B列中值为'two'的记录,其他行的B列设为缺失值。下面是几种简单可行的实现方式:

方法1:使用DataFrame.where()(最简洁)

where()方法会保留满足条件的元素,不满足的会替换为NaN,完美匹配你的需求:

df['B'] = df['B'].where(df['B'] == 'two')

执行后得到的结果:

AB
1NaN
2two
3NaN
4two
5NaN

方法2:布尔索引直接赋值

这种方式更直观,直接定位到B列中不等于'two'的行,把它们设为缺失值:

import numpy as np
# 或者用 pd.NA(适合pandas 1.0+版本)
df.loc[df['B'] != 'two', 'B'] = np.nan

通用化方案(适配任意列和目标值)

如果以后需要对其他列、其他值做同样操作,可以封装成一个函数,复用性拉满:

def keep_target_value_keep_rows(df, target_col, target_value):
    # 先复制原DataFrame,避免修改原始数据
    result_df = df.copy()
    result_df[target_col] = result_df[target_col].where(result_df[target_col] == target_value)
    return result_df

# 使用示例:对B列保留'two'
filtered_df = keep_target_value_keep_rows(df, 'B', 'two')
# 也可以换其他列,比如对C列保留'foo'
# filtered_df = keep_target_value_keep_rows(df, 'C', 'foo')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:04:33