0

I would like my code to look at column one first. If it has a valid number for that row, take that value as the COL 3 value. If not, the second option would be to take the value of COL 2 as the value in COL 3. Is there a Function that can do this?

     COL1  COL2  COL3
0     1     2
1    nan    4
2     3    nan
3     4     8
4    nan    10
5     6    nan

     COL3   
0     1    
1     4   
2     3   
3     4   
4     10
5     6
anky
  • 74,114
  • 11
  • 41
  • 70
machinelearner07
  • 113
  • 1
  • 1
  • 12

2 Answers2

3

try this

df['col 3'] = np.where(df['col 1'].isnull(),df['col 2'],df['col 1'])
tawab_shakeel
  • 3,701
  • 10
  • 26
-2

IIUC:

df['COL3'] = df.bfill(axis=1)['COL1']

gives:

   COL1  COL2  COL3
0   1.0   2.0   1.0
1   NaN   4.0   4.0
2   3.0   NaN   3.0
3   4.0   8.0   4.0
4   NaN  10.0  10.0
5   6.0   NaN   6.0
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • 1
    Just a kind suggestion this type of common question better mark dup instead of answer – BENY Jun 26 '19 at 16:12
  • Noted, it's just so much easier to answer than look for dup. – Quang Hoang Jun 26 '19 at 16:13
  • That is true :-) – BENY Jun 26 '19 at 16:14
  • 2
    "Noted, it's just so much easier to answer than look for dup." that's not an acceptable reason, to be honest. Just FYI, we are trying to reduce clutter in this tag because there are too many duplicates asked on a daily basis. We could answer them as well but we refrain because it is not good for the site to fragment information across multiple posts. – cs95 Jun 26 '19 at 16:16