有没有什么方法可以减少条件语句中的代码

2024-05-19 15:19:58 发布

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

我想把上图中的代码简化为条件语句中的简短代码。在这篇文章中,我试图将BHK转换成整数值,以便在机器学习中使用它。你知道吗

def replace_size(string):
    if string == '1 RK':
        return 0
    elif string == '1 BHK' or string == '1 Bedroom':
        return 1
    elif string == '2 BHK' or string == '2 Bedroom':
        return 2
    elif string == '3 BHK' or string == '3 Bedroom':
        return 3
    elif string == '4 BHK' or string == '4 Bedroom':
        return 4
    elif string == '5 BHK' or string == '5 Bedroom':
        return 5
    elif string == '6 BHK' or string == '6 Bedroom':
        return 6
    elif string == '7 BHK' or string == '7 Bedroom':
        return 7
    elif string == '8 BHK' or string == '8 Bedroom':
        return 8
    elif string == '9 BHK' or string == '9 Bedroom':
        return 9
    elif string == '10 BHK' or string == '10 Bedroom':
        return 10
    elif string == '11 BHK' or string == '11 Bedroom':
        return 11
    elif string == '12 BHK' or string == '12 Bedroom':
        return 12
    elif string == '13 BHK' or string =='13 Bedroom':
        return 13
    elif string == '14 BHK' or string =='14 Bedroom':
        return 14
    elif string == '16 BHK' or string =='16 Bedroom':
        return 16
    elif string == '18 BHK' or string =='18 Bedroom':
        return 18
    elif string == '19 BHK' or string =='19 Bedroom':
        return 19
    elif string == '27 BHK' or string =='27 Bedroom':
        return 27
    elif string == '43 BHK' or string =='43 Bedroom':
        return 43

我尝试使用包含'1 Bedroom'、'1 BHK'和'1 RK'的pandas系列,然后对系列使用apply(replace\ u size)函数来获得int类型值的pandas系列。你知道吗

谢谢1


Tags: or代码pandassizestringreturn整数语句
3条回答

只是一个简单的想法,也许你可以用这样的方法:

def replace_size(string):
    if string == '1 RK':
        return 0
    else:
        for i in range(1, 44):
            if str(i) in string:
                return i

到目前为止,这也许不是最好的答案,但也许它会引导你朝着正确的方向前进。 我也不知道你可能的数据,如果有任何数字高于你提到的43可能发生。你知道吗

import re


def replace_size(string):
    if string == '1 RK':
        return 0
    elif re.match("\d{1,2} BHK|\d{1,2} Bedroom", string):
        return int(string.split(' ')[0])
def replace_size(string):
    if string == '1 RK':
        return 0
    else:
        st = string.split(' ')
        return int(st[0]) if  (st[1] == "BHK" or  st[1] == "Bedroom") else None

相关问题 更多 >