Pandas DataFrame.where() 方法详解

DataFrame.where() 介绍

DataFrame.where() 函数允许我们根据特定条件替换 DataFrame 中的值。它的核心逻辑是:在条件为 True 时保留原始值,而在条件为 False 时将其替换为其他值(例如 NaN 或自定义数值)。这是一种非常直观的数据筛选与清洗方式。
举个例子:

Python

import pandas as pd
import numpy as np
df = pd.DataFrame({‘A‘: [1, -2, 3], ‘B‘: [-1, 5, -6]})

res = df.where(df > 0)
print(res)

输出结果

A    B
0  1.0  NaN
1  NaN  5.0
2  3.0  NaN

原理解析:df.where(df > 0) 中,我们保留了所有大于 0 的值,而将不满足该条件(小于或等于 0)的值替换为了 NaN。

语法

> DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise‘, try_cast=False)

参数说明:

参数

描述

cond

需要检查的条件(可以是布尔类型的 DataFrame 或 Series)

other

当条件为 False 时用于替换的值(默认为 NaN)

inplace

如果为 True,将直接在原 DataFrame 上进行修改

axis

用于对齐条件的轴方向

level

用于多层索引 的匹配

errors

如果为 ‘raise‘,遇到错误将抛出异常;如果为 ‘ignore‘,则忽略错误

trycast

尝试将结果转换回原始的数据类型返回值: 返回替换值后的 DataFrame(如果 INLINECODE7c2014a6,则返回 None)

示例

示例 1: 在这个例子中,我们将使用 other 参数把所有负数替换为 0。

Python

import pandas as pd
df = pd.DataFrame({‘A‘: [1, -2, 3], ‘B‘: [-1, 5, -6]})

res = df.where(df > 0, other=0)
print(res)

输出结果

A  B
0  1  0
1  0  5
2  3  0

原理解析: where(df > 0, other=0) 保留了所有大于 0 的数值,并将所有负数替换为 0,正数保持不变。
示例 2: 这里我们演示如何直接修改原 DataFrame,将所有小于或等于 0 的值替换为 NaN。

Python

import pandas as pd
df = pd.DataFrame({‘A‘: [2, -3, 4], ‘B‘: [-5, 6, -7]})

df.where(df > 0, inplace=True)
print(df)

输出结果

A    B
0  2.0  NaN
1  NaN  6.0
2  4.0  NaN

原理解析: 设置 INLINECODE7f3d9a21 会直接将更改应用到 INLINECODE0fac5795 变量上,无需再将结果赋值给一个新变量。
示例 3: 在本例中,我们将使用 Series 而不是完整的 DataFrame 来应用条件。

Python

import pandas as pd
df = pd.DataFrame({‘Score‘: [45, 85, 60, 30]})
condition = df[‘Score‘] >= 50

res = df.where(condition, other=‘Fail‘)
print(res)

输出结果

Score
0  Fail
1    85
2    60
3  Fail

原理解析: 只有大于等于 50 分的成绩被保留,其余分数均被替换为字符串 ‘Fail‘。

> 相关文章: DataFrame 详解

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/37682.html
点赞
0.00 平均评分 (0% 分数) - 0