Pandas dataframe If else具有逻辑且包含两列

2024-10-01 05:03:15 发布

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

如何在包含pandas数据帧的两列的控制语句中添加逻辑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']中包含一个附加条件:

^{pr2}$

ValueError: ('Arrays were different lengths: 6132 vs 2', u'occurred at index 0')


Tags: and数据inpandasifdeflocationval
1条回答
网友
1楼 · 发布于 2024-10-01 05:03:15

您需要使用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

相关问题 更多 >