Priority formula in excel or python pandas

Viewed 37

Let's say there are two columns in Excel:

A                B
tim@email.com  josh@email.com
math@email.com angel@email.com
nil@email.com  noemail
               jorme@email.com 

I want to put a condition such as:

       A        B                   C
tim@email.com  josh@email.com  josh@email.com
math@email.com angel@email.com angel@email.com
nil@email.com  noemail         nil@email.com     
               jorme@email.com jorme@email.com

Setting priority to B and if not available any email at b then take from A.

Pandas and Excel formula both will be ok.

2 Answers

Let's consider that valid addresses in A contain a @ character:

df['C'] = df['B'].where(df['B'].str.contains('@'), df['A'])

# or if you don't want to fill with potentially invalid addresses in B
# df['C'] = df['B'].where(df['B'].str.contains('@'),
#                         df['A'].where(df['A'].str.contains('@')))

Or testing if the value is not 'noemail':

df['C'] = df['B'].where(df['B'].ne('noemail'), df['A'])

output:

                A                B                C
0   tim@email.com   josh@email.com   josh@email.com
1  math@email.com  angel@email.com  angel@email.com
2   nil@email.com          noemail    nil@email.com
3                  jorme@email.com  jorme@email.com

I achieved desired result by using excel if conditions , See below

enter image description here

In column C, Paste below formula

=IF(B1="noemail",A1,B1)

Note : you should mark "noemail" if no email id is present in column B .

Related