开发者社区> 问答> 正文

使用pandas的IF和ELIF功能

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

我在Pandas数据框中有一个列,我想检查这些值是否在设定范围之间。我选择这样做是通过创建一个接受数据帧作为参数的函数,并使用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)

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

展开
收起
一码平川MACHEL 2019-01-16 17:19:29 3514 0
1 条回答
写回答
取消 提交回答
  • 我知道你的问题特别要求一个将数据帧作为参数的函数,但我觉得你的方法破坏了数据帧的强度。我会选择直接转型方法

    import pandas as pd

    df = pd.read_csv('your_data_source.csv')

    Function output in a new column fn_A

    df['fn_A'] = df[df['A'].apply(lambda x: x < 125)]['A'].apply(lambda y: 935 + 0.2 * y)
    df['fn_A'] = df[df['A'].apply(lambda x: 955 < x < 974)]['A'].apply(lambda y: 921.2 + 0.2 * (y - 955))
    df['fn_A'] = df[df['A'].apply(lambda x: 975 < x < 1023)]['BCCH'].apply(lambda y: 925.2 + 0.2 * (y - 975))
    df['fn_A'] = df[df['A'].apply(lambda x: 511 < x < 885)]['A'].apply(lambda y: 1805.2 + 0.2 * (y - 512))


    您可以利用它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.where

    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'))))
    
    2019-07-17 23:25:41
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
中文:即学即用的Pandas入门与时间序列分析 立即下载
即学即用的Pandas入门与时间序列分析 立即下载
低代码开发师(初级)实战教程 立即下载