Python Forum
compare and modify columns in dataframe - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: compare and modify columns in dataframe (/thread-16051.html)



compare and modify columns in dataframe - DionisiO - Feb-12-2019

Hello all,

I'm have loaded a csv file into a dataframe using pandas. I want to compare the numbers in two columns, if col A is the same as col b, do this. If Col a is > col b, do this. and so on.

I'm pretty sure there is a shorter way to do this. Here is my code:

Thanks!!

for index,row in puntos.iterrows():

    if row["localGoals"] > row["visitorGoals"]:        
        puntos["PuntosLocal"] = 3
        puntos["PuntosVisitante"] = 0
        print(row["localGoals"])
    elif row["localGoals"] < row["visitorGoals"]:
        puntos['PuntosLocal'] = 0
        puntos['PuntosVisitante'] = 3
    else:
        puntos['PuntosLocal'] = 1
        puntos['PuntosVisitante'] = 1



RE: compare and modify columns in dataframe - tiredAcademic - Feb-23-2019

Hi DionisiO,

There are a number of ways to write shorter versions of what your code does (at least without the [printing), for example...

In four lines:
puntos.loc[puntos.localGoals > puntos.visitorGoals, 'PuntosLocal'] = 3
puntos.loc[puntos.localGoals < puntos.visitorGoals, 'PuntosLocal'] = 0
puntos.loc[puntos.localGoals == puntos.visitorGoals, 'PuntosLocal'] = 1
puntos['PuntosVisitante'] = puntos.PuntosLocal.map(lambda pl: {3: 0, 0: 3, 1: 1}[pl])
or in "one" line:
puntos['PuntosLocal'], puntos['PuntosVisitante'] = zip(*[
    (3, 0) if local > visitor else (0, 3) if local < visitor else (1, 1)
    for local, visitor in zip(puntos.localGoals, puntos.visitorGoals)
])
On the other hand, I read your code and knew exactly what it did within a couple seconds. Can you honestly do that for either of my options? Your code is reasonably efficient, and very readable - not too bad!