Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 compare and modify columns in dataframe
#1
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
Quote
#2
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!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  display graph in columns and rows william888 1 172 Jul-02-2019, 10:19 AM
Last Post: dataman
  [pandas] How to re-arrange DataFrame columns SriMekala 8 539 Jun-22-2019, 12:55 AM
Last Post: scidam
  Apply function on different columns as defined DavidGG 5 492 Jun-03-2019, 01:12 PM
Last Post: ichabod801
  The combination of four columns in two. pawlo392 2 248 May-31-2019, 01:54 PM
Last Post: heiner55
  How to modify video using pixel array or shader? jhovarie 1 754 May-26-2019, 10:52 AM
Last Post: heiner55
  Pandas - cumulative sum of two columns tobbs 12 538 May-25-2019, 08:37 PM
Last Post: tobbs
  Selecting Few Columns from a dataframe Shivi_Bhatia 2 268 Mar-24-2019, 12:20 PM
Last Post: Shivi_Bhatia
  Grab columns from multiple files, combine into one jon0852 0 266 Feb-12-2019, 02:53 AM
Last Post: jon0852
  How to modify and save a column in the sqlite3 database using python? laithsky1 3 413 Dec-18-2018, 03:39 AM
Last Post: micseydel
  Extracting specific columns in an array uthongam 1 337 Dec-07-2018, 06:06 PM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)