简体   繁体   中英

compare 2 columns in dataframe and save conditions in another column in same dataframe

I want to compare each value in "Inforce Counts" and "vlookup".

  • If "vlookup" is "N/A" then "comparision" should be "N/A"
  • If counts match then "comparision" should be "True"
  • If counts not match then "comparision" should be "False"

df1: 在此处输入图像描述

expected output:

在此处输入图像描述

If you prefer to use pandas libraries there a good way too.

The simplest way and more efficient (fastest) is using the function df.apply of the data frame. First define the function of how you calculate the new column, and then apply it with the apply function:

def creating_new_column(row):
    #Create your conditions
    if row["vlookup"]=="N/A":
         return ("N/A")
    
    elif row["vlookup"]==row["Inforce Counts"]:
         return(True)

    else:
         return(False)

An then use apply :

df["comparision"]=df.apply(lambda row: creating_new_column (row), axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM