我正在编写一条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