0

I'm trying to combine two columns into a third based on the values. Original data

|Time|  GearUp | GearDn|
|----|---------|-------|  
| 1  |   NaN   |  NaN  |
|2   |  NaN    | DOWN  |
|3   |  NaN    | NaN   |
|4   |  NaN    | NaN   |
|5   |  UP     | NaN   |
|6   |  NaN    | NaN   |
|7   |  NaN    | NaN   |

Required result:

Time  Gear
1     NaN     
2     DOWN
3     DOWN
4     DOWN
5     UP     
6     UP     
7     UP    

I tried using the where method but on each column in turn but the second use wrote over the data from the first time.

Thanks.

2 Answers2

0

use

df['Gear'] = df['GearUp'].combine_first(df['GearDown'])

refer this link for documentation https://pandas.pydata.org/docs/reference/api/pandas.Series.combine_first.html

Deepan
  • 430
  • 4
  • 13
0

use ffill to fill the NaN values (addition to Deepan Solution)

df['Gear']=df['GearUp'].combine_first(df['GearDn']).ffill()
df
    Time    GearUp  GearDn  Gear
0      1       NaN     NaN  NaN
1      2       NaN     DOWN DOWN
2      3       NaN     NaN  DOWN
3      4       NaN     NaN  DOWN
4      5       UP      NaN  UP
5      6       NaN     NaN  UP
6      7       NaN     NaN  UP
Naveed
  • 11,495
  • 2
  • 14
  • 21