如何在Python match/case语句中匹配Pandas DataFrame的NaN值?
在Python match/case中匹配Pandas DataFrame里的NaN值
问题原因
直接用case np.nan:匹配不到NaN,核心原因是NaN的特殊性质:np.nan == np.nan会返回False,而match/case的匹配逻辑基于相等性判断,因此无法命中该分支。
解决方案
方案1:使用守卫条件(Guard Clause)
在case中结合pd.isna()做前置判断,这是最直接的修改方式:
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 _ 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" result = df["col"].apply(handle_col) print(result)
输出:
0 this is another string 1 this is letter a 2 this is letter b 3 not a number Name: col, dtype: object
方案2:将NaN转换为可直接匹配的类型
把NaN替换成None(None可以直接通过case None:匹配):
import pandas as pd import numpy as np data = {'col': ["foo", "a", "b", np.nan]} df = pd.DataFrame(data) def handle_col(n): # 先将NaN转为None n = None if pd.isna(n) else n match n: case None: return "not a number" case "a": return "this is letter a" case "b": return "this is letter b" case _: return "this is another string" result = df["col"].apply(handle_col) print(result)
方案3:使用Pandas向量化操作替代apply(更高效)
如果处理大数据集,apply的循环效率较低,可以用Pandas向量化方法实现相同逻辑:
import pandas as pd import numpy as np data = {'col': ["foo", "a", "b", np.nan]} df = pd.DataFrame(data) # 用np.where和map组合实现 df['col_processed'] = np.where( pd.isna(df['col']), "not a number", df['col'].map({ "a": "this is letter a", "b": "this is letter b" }).fillna("this is another string") ) print(df['col_processed'])
内容的提问来源于stack exchange,提问作者gru
相关产品推荐
相关产品推荐

