我正在编写一条Python Match/Case语句,我想将其应用于Pandas 数据帧.但是数据中有一堆NaN值,如果不在缺省情况下处理它们,我不知道如何处理它们,因为我希望缺省情况下做一些其他的事情

如何匹配NaN值?

以下是我try 过但不起作用的示例代码:

import pandas as pd
import numpy as np

data = {'col': ["foo", "a", "b", np.nan]}
df = pd.DataFrame(data)

def handle_col(n):
    match n:
        case np.nan:
            return "not a number"
        case "a":
            return "this is letter a"
        case "b":
            return "this is letter b"
        case _:
            return "this is another string"
    
df["col"].apply(handle_col)

以下是输入数据帧

    col
0   foo
1   a
2   b
3   NaN

而我得到的(错误)答案是:

0    this is another string
1          this is letter a
2          this is letter b
3    this is another string
Name: col, dtype: object

推荐答案

问题是空值不遵守等式判断,即,np.nan == np.nanFalse,解决方案是在case中使用防护:

def handle_col(n):
    match n:
        case _ if pd.isna(n):
            return "not a number"
        case "a":
            return "this is letter a"
        case "b":
            return "this is letter b"
        case _:
            return "this is another string"

df["col"].apply(handle_col)

0    this is another string
1          this is letter a
2          this is letter b
3              not a number
Name: col, dtype: object

Python-3.x相关问答推荐

如何匹配字母,数字,短划线,逗号,但不是如果没有数字和字母?

使用 Fetch 提交表单到 Django 视图

数据框中从每个组/ID的底部删除行

如何将多输入数据加载器传递给单输入模型

pytorch 中 mps 设备的 manual_seed

Python:如何从句子/段落中提取地址(非正则表达式方法)?

FastAPI - 调用 API 时设置 response_model_exclude

请求:RecursionError:超出最大递归深度

具有函数值的 Python 3 枚举

python tkInter 浏览文件夹按钮

错误:预期语句,发现 py:Dedent

python 3.4版不支持'ur'前缀

TypeError:列表索引必须是整数或切片,而不是列表

Python中的多行日志(log)记录

PIL 在图像上绘制半透明方形覆盖

如何使用 python 库连接到 poloniex.com websocket api

如何在 jupyter notebook 5 中逐行分析 python 3.5 代码

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python

使用 Python 3 读取 CSV 文件

如何将python日志(log)级别名称转换为整数代码