How to create a new dataframe column from existing columns using if-else
Question:
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?
Answers:
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
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?
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