如何在涉及熊猫数据帧两列的控制语句中添加逻辑AND

这有效:

def getContinent(row):
    if row['Location'] in ['US','Canada']:
        val = 'North America'
    elif row['Location'] in['UK', 'Germany']:
        val = 'Europe'
    else:
        val = None
    return val

df.apply(getContinent, axis=1)


现在,我想在另一个字段row['Sales']中加入一个附加条件:

def getContinent(row):
    if row['Location'] in ['US','Canada'] & row['Sales'] >= 100:
        val = 'North America'
    elif row['Location'] in['UK', 'Germany'] & row['Sales'] < 100:
        val = 'Europe'
    else:
        val = None
    return val

df.apply(getContinent, axis=1)



  ValueError:('数组的长度不同:6132 vs 2',u'发生在索引0')

最佳答案

您需要使用and代替&

df = pd.DataFrame({'Sales': {0: 400, 1: 20, 2: 300},
                   'Location': {0: 'US', 1: 'UK', 2: 'Slovakia'}})
print (df)

   Location  Sales
0        US    400
1        UK     20
2  Slovakia    300

def getContinent(row):
    if row['Location'] in ['US','Canada'] and row['Sales'] >= 100:
        val = 'North America'
    elif row['Location'] in['UK', 'Germany'] and row['Sales'] < 100:
        val = 'Europe'
    else:
        val = None
    return val

print (df.apply(getContinent, axis=1))
0    North America
1           Europe
2             None
dtype: object

关于python - Pandas数据框,如果具有逻辑AND,则涉及两列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39016405/

10-12 23:36