函数与IF和ELIF一起使用

2024-06-03 17:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

定义检查列是否在给定整数范围内的函数的更好方法(如果有的话)是什么?你知道吗

在Pandas数据帧中有一个列,我想检查这些值是否在设置的范围内。我选择通过创建一个函数来实现,该函数接受dataframe作为参数,并使用IF和ELIF测试列是否在范围内。 在范围较小的情况下,这可能是正常的,但是如果范围较大,则生成的if,ELIF函数可能难以维护。有没有更好的方法来实现这一点?你知道吗

我的代码-

def fn(dframe):
    if dframe['A'] < 125:
        return 935 + 0.2 * dframe['A']

    elif (dframe['A'] >= 955) and (dframe['A'] <= 974):
        return 921.2 + 0.2 * (dframe['A'] - 955)

    elif (dframe['A'] >= 975) and (dframe['A'] <= 1023):
        return 925.2 + 0.2 * (dframe['BCCH'] - 975)

    elif (dframe['A'] >= 511) and (dframe['A'] <= 885):
        return 1805.2 + 0.2 * (dframe['A'] - 512)

此代码按预期工作,但是如果范围较大,则结果函数很难管理。你知道吗

编辑:

谢谢@ycx,@Jorge和所有人-我喜欢你代码的可读性。不过,我想知道@ycx的方法是否在csv文件中有“condlist”的最小值和最大值-例如

condlist_from_CSV_file

然后我可以把它读入数据帧。现在,我想检查另一个数据帧中列'a'的每一行是否都在这些限制之间,如果为真,则返回相应的'Choice',否则返回'None',这有意义吗? 期望输出-

output dataframe with check

以此类推。。你知道吗


Tags: and数据方法函数代码dataframereturnif
2条回答

您可以使用np.select来管理您的条件和选项。这使您可以轻松地维护条件和选项,并使用numpy库函数,这有助于加快代码的速度

def fn(dframe):
    import numpy as np
    condlist = [
            dframe['A'] < 125, 
            (dframe['A'] >= 955) and (dframe['A'] <= 974),
            (dframe['A'] >= 975) and (dframe['A'] <= 1023),
            (dframe['A'] >= 511) and (dframe['A'] <= 885),
            ]
    choicelist = [
            935 + 0.2 * dframe['A'],
            921.2 + 0.2 * (dframe['A'] - 955),
            925.2 + 0.2 * (dframe['BCCH'] - 975),
            1805.2 + 0.2 * (dframe['A'] - 512),
            ]
    output = np.select(condlist,choicelist)
    return output

看来你需要np.哪里你知道吗

import numpy as np
np.where(dframe['A'] < 125, 935 + 0.2 * dframe['A'],
       np.where(dframe['A'] >= 511) & (dframe['A'] <= 885), 1805.2 + 0.2 * (dframe['A'] - 512,
       np.where(dframe['A'] <= 974, 921.2 + 0.2 * (dframe['A'] - 955),
       np.where(dframe['A'] <= 1023, 925.2 + 0.2 * (dframe['A'] - 975),
    'Value for any other value'))))

相关问题 更多 >