首页 > 解决方案 > 遍历两个列表/列,条件添加到第三个列表/列

问题描述

我正在做一个任务,我目前面临一个挑战,希望有人能够帮助我。
我有两列或列表(更适合的),我想迭代以将结果添加到第三列。它是自 2016 年原始数据库以来的英超联赛数据集,它将有条件设置获胜、失败和平局,将获得或不获得的积分添加到第 3 列/列表中。
谢谢

def pointsF(df):
x, y = list(df['score1']), list(df['score2'])
#x, y = iter(xl), iter(yl)
g = 0
r = list()

#for (i, z) in itertools.zip_longest(x, y):
for x, y in zip(x, y):
    if x == y:
        g = g +1
        r.append(g)
        next

        
    elif x > y:
        g = g+3
        r.append(g)
        next

    else:
        g = g
        r.append(g)
        next
    return r

标签: python-3.xdataframefor-loopiteration

解决方案


如果有人遇到同样的情况,这是我发现的最好的解决方案!

cond1 = [ (dfPL['GoalsHome'] > dfPL['GoalsAway']), (dfPL['GoalsHome'] < dfPL['GoalsAway']), (dfPL['GoalsHome'] == dfPL['GoalsAway'])]


#choices result and points
cc = ['w','l','d']
ccp = [3,0,1]
dfPL['HomeResult'] = np.select(cond1, cc, default=0 )

推荐阅读