dimanche 14 février 2021

IF statement for dataframes in Python

I have a dataset that looks like this.

Conatct 1 Contact 2 Contact 3
NA XYZ STU
NA NA LMN
ABC PQR NA

I'm trying to write a new column which will consolidate the contact information from the three different columns into one consolidated column such that if Contact 1 is NA then contact information from Contact 2 will be picked up and if Contact 2 is also empty then Contact 3 will get picked up. Below is the code I have so far.

def rm_contact(row):
   if row["LOB Contact #1"] != "NA":
     return row["Contact 1"]      
   else:
     return row["Contact 2"] 

df2 = df2.assign(rm=df2.apply(rm_contact, axis=1))

The else part of the code doesn't seem to work. So even though Contact 1 is NA the details from Contact 2 or Contact 3 don't get filled in properly. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire