I have a dataframe as seen below:
JavaScript
x
7
1
col_a1, col_a2, col_b1, col_b2
2
abc lmn
3
def ghi qrs
4
zxv vbn
5
pej iop qaz
6
eki lod yhe wqe
7
I need two columns now, column A and Column B. Conditions summarized:
JavaScript
1
3
1
Column A = col_a2 if col_a2 is present else col_a1
2
Column B = col_a1 if col_a1 is present else col_b2
3
The required dataframe should be as follows:
JavaScript
1
7
1
Column A Column B
2
abc lmn
3
ghi qrs
4
zxv vbn
5
pej iop
6
lod yhe
7
Advertisement
Answer
Try:
JavaScript
1
11
11
1
df['A'] = df.apply(lambda x: x['col_a2'] if x['col_a2'] != '' else x['col_a1'], axis=1)
2
df['B'] = df.apply(lambda x: x['col_b1'] if x['col_b1'] != '' else x['col_b2'], axis=1)
3
print(df[['A', 'B']])
4
5
A B
6
0 abc lmn
7
1 ghi qrs
8
2 zxv vbn
9
3 pej iop
10
4 lod yhe
11
The !=''
will work if you truly have nothing in the cell (as opposed to a NaN
etc.). If you have actual NaN values use:
JavaScript
1
3
1
df['A'] = df.apply(lambda x: x['col_a2'] if pd.notna(x['col_a2']) else x['col_a1'], axis=1)
2
df['B'] = df.apply(lambda x: x['col_b1'] if pd.notna(x['col_b1']) else x['col_b2'], axis=1)
3