Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a new dataframe column from existing columns using if-else

I have data frame and target value like this:

target = 'Math'

df:
Col1   Col2 
Math   Science
Music  Math
Social Math
Arts   Math

I want to create a new column(New_Col) such that 
if Col1 == target i.e Math:
    New_Col = Col2 value
else:
    New_Col = Col1 value

So the output looks like this:

df:

Col1   Col2        New_Col
Math   Science      Science
Music  Math         Music
Social Math         Social
Arts   Math         Arts

Can anyone help me with this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

My solution:

import pandas as pd

a = {'Col1':['Math', 'Music', 'Social','Arts'],  'Col2':['Science','Math', 'Math', 'Math']}
 
df = pd.DataFrame(a)
#if Col1 != Math: copy Col1
df['New_Col'] = df[df['Col1'] != 'Math' ]['Col1']
#if Col1 == Math: copy Col2
df.loc[df['New_Col'].isna(), 'New_Col'] = df[ df['Col1']== 'Math' ]['Col2']
df

Output:

     Col1     Col2  New_Col
0    Math  Science  Science
1   Music     Math    Music
2  Social     Math   Social
3    Arts     Math     Arts
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading