Skip to main content
 首页 » 编程设计

python之Pandas Series.apply() 没有按预期工作

2025年05月04日26Terrylee

我正在尝试应用一个函数来检查存储在系列中的字符串是否为数字,如果是,则将它们变为 None,如果不是,则什么也不做。系列如下:

0 'EUR' 
1 '327' 
2 'None' 
3 'USD' 

检查条目是否为表示为字符串的数字的函数:

def is_number(s): 
    try: 
        float(s) 
        return True 
    except (TypeError,ValueError): 
        pass 
 
    try: 
        import unicodedata 
        unicodedata.numeric(s) 
        return True 
    except (TypeError, ValueError): 
        pass 
 
    return False 
 
 
def num_to_none(target): 
    if is_number(target): 
        target = None 

我这样调用函数:

result = mySeries.apply(num_to_none) 

但是我得到以下 res 的结果:

    0 'None' 
    1 'None' 
    2 'None' 
    3 'None' 

期望的结果是:

0 'EUR' 
1 'None' 
2 'None' 
3 'USD' 

我目前只是在一个小数据框(10000 行,70 列)的测试环境中尝试这个,但如果我可以让它工作,我希望将它应用到更大的数据框,因此也欢迎提出效率建议。提前致谢。

请您参考如下方法:

您需要返回num_to_none 函数的结果

def num_to_none(target): 
    if is_number(target): 
        target = None 
    return target 

你的函数表现不正常的原因是,如果没有 return 语句,默认行为是 return None

例子

def my_function(): 
    print "hello world" 

相当于

def my_function(): 
    print "hello world" 
    return None