numpy 函数中的try except返回错误消息

2w2cym1i  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(134)

我有一个矢量化的函数,它可以对一个数字进行简单的调整

import pandas as pd
import numpy as np

@np.vectorize
def adjust_number(number: int) -> int:

    max_number = 6
    default_substitue = 2

    # Try to convert to int, if not possible, use default_substitue
    try:
        number = int(number)
    except:
        number = default_substitue

    return min(number, max_number)

我把这个函数应用到一个

df = pd.DataFrame({'numbers': [1.0, 9.0, np.nan]})
df = df.assign(adjusteded_number=lambda x: adjust_number(x['numbers']))

这将返回预期的输出,但我也会得到一条奇怪的返回消息

c:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\lib\function_base.py:2412: RuntimeWarning: invalid value encountered in adjust_number (vectorized)
outputs = ufunc(*inputs)

这不是一个大问题,但它非常烦人。错误似乎是由try-except触发的。如果我修改函数,删除try-except,我真的不能这样做,而不破坏功能,错误消失。
是什么导致了这个问题,我如何才能摆脱错误消息?

uqxowvwt

uqxowvwt1#

如果你担心的是NaN的/infinities,你可以使用NumPy isfinite函数来检查这些:

@np.vectorize
def adjust_number(number: int) -> int:
    max_number = 6
    default_substitue = 2

    # Try to convert to int, if not possible, use default_substitue
    if np.isfinite(number):
        number = int(number)
    else:
        number = default_substitue

    return min(number, max_number)

如果你还想确保这个数字实际上也是一个整数,即使它是一个浮点数,你可以这样做:

@np.vectorize
def adjust_number(number: int) -> int:
    max_number = 6
    default_substitue = 2

    # Try to convert to int, if not possible, use default_substitue
    if np.isfinite(number):
        # make sure number is integer
        if isinstance(number, int) or (isinstance(number, float) and number.is_integer()):
            number = int(number)
        else:
            default_substitute
    else:
        number = default_substitue

    return min(number, max_number)

或者,你甚至不需要使用vectorize,而是可以这样做:

def adjust_number(number):
    default_substitute = 2
    max_number = 6
    num = np.asarray(number)  # make sure input is array
    num[~np.isfinite(num)] = default_substitute
    return np.clip(num, a_min=None, a_max=max_number).astype(int)

相关问题