将if-else函数应用于python/python中的两个字符串列

2024-09-26 18:05:34 发布

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

在我的数据框中,我有:

Name    Sex    Height
Jackie   F       Small
John     M       Tall

我使用了以下函数来创建基于组合的新列:

def genderfunc(x,y):
    if x =='Tall' & y=='M':
        return 'T Male'
    elif x =='Medium' & y=='M':
        return 'Male'
    elif x =='Small' & y=='M':
        return 'Male'
    elif x =='Tall' & y=='F':
        return 'T Female'
    elif x =='Medium' & y=='F':
        return 'Female'
    elif x =='Small' & y=='F':
        return 'Female'
    else:
        return y

应用此功能的我的代码行:

df['GenderDetails'] = df.apply(genderfunc(df['Height'],df['Sex']))

我得到以下信息:

TypeError: Cannot perform 'rand_' with a dtyped [object] array and scalar of type [bool]

你知道我做错了什么吗?这是我第一次尝试使用函数

谢谢


Tags: 数据函数namedfreturnmalefemalesmall
2条回答

您需要将&替换为and

如果性能是一个问题,您也可以使用np.select,

condlist = [(df['Height'] == 'Tall') & (df['Sex'] == 'M'),
            (df['Height'] == 'Medium') & (df['Sex'] == 'M'),
            (df['Height'] == 'Small') & (df['Sex'] == 'M'),
            (df['Height'] == 'Tall') & (df['Sex'] == 'F'),
            (df['Height'] == 'Medium') & (df['Sex'] == 'F'),
            (df['Height'] == 'Small') & (df['Sex'] == 'F')]
choiselist = [
    'T Male',
    'Male',
    'Male',
    'T Female',
    'Female',
    'Female'
]

df['GenderDetails'] = np.select(condlist, choiselist, df['Sex'])

相关问题 更多 >

    热门问题