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
  Selecting Few Columns from a dataframe Shivi_Bhatia 2 140 Mar-24-2019, 12:20 PM
Last Post: Shivi_Bhatia
  Grab columns from multiple files, combine into one jon0852 0 175 Feb-12-2019, 02:53 AM
Last Post: jon0852
  How to modify and save a column in the sqlite3 database using python? laithsky1 3 289 Dec-18-2018, 03:39 AM
Last Post: micseydel
  Extracting specific columns in an array uthongam 1 228 Dec-07-2018, 06:06 PM
Last Post: ichabod801
  HOw define the colors for two columns? Jack_Sparrow 3 540 Jun-15-2018, 06:46 PM
Last Post: snippsat
  Trying to clean the selected columns paulgureghian 5 656 Jun-08-2018, 10:08 PM
Last Post: volcano63
  comparing two columns two different files in pandas nuncio 0 402 Jun-06-2018, 01:04 PM
Last Post: nuncio
  Dropping all rows of multiple columns after the max of one cell Thunberd 2 447 Jun-01-2018, 10:18 PM
Last Post: Thunberd
  How to compare two files and Display different results for text and for INT Prince_Bhatia 1 436 May-18-2018, 11:52 AM
Last Post: Prince_Bhatia
  subtruction of columns in pandas garikhgh0 3 606 May-14-2018, 10:31 AM
Last Post: volcano63

Forum Jump:


Users browsing this thread: 1 Guest(s)