I have a df with 2 columns like below:
A B 0 100-00 nan 1 200-00 nan 2 other 300-00 3 100-00 text 4 other nan I need to create column C which will apply logic as below:
- if B is nan, then A
- if B starts with numeric, then B
- else A
I've got code as below, which is working just fine, but I believe there might be a better, more efficent way to do it:
C = [] for r in range(df.shape[0]): if df['B'].iloc[r] == 'nan': C.append(df['A'].iloc[r]) elif df['B'].iloc[r][:3].isnumeric(): C.append(df['B'].iloc[r]) else: C.append(df['A'].iloc[r]) df['C'] = C df A B C 0 100-00 nan 100-00 1 200-00 nan 200-00 2 other 300-00 300-00 3 100-00 text 100-00 4 other nan other Thanks in advance for all your help.