djj1994
djj1994

Reputation: 55

Python: replace "NA" in column with value from corresponding row value of another column (and vice versa)

I have the following dataframe:

RawTimes_df =

                  ETime              XTime
0     2018-05-21 04:48:22  2018-05-21 05:52:45
1     2018-05-21 02:18:20  2018-05-21 03:19:53
2     2018-05-21 11:02:31  2018-05-21 12:17:57
3     2018-05-21 06:08:15  2018-05-21 07:08:12
4     NA                   2018-05-21 16:14:16
5     2018-05-21 03:38:12  2018-05-21 04:39:05
6     2018-05-21 17:43:06  2018-05-21 18:59:38
7     2018-05-21 08:52:32  NA
8     2018-05-21 02:27:44  2018-05-21 03:33:08
9     2018-05-21 12:01:12  NA
10    2018-05-21 10:21:10  2018-05-21 11:26:45
11    NA                   2018-05-21 21:27:38
12    2018-05-21 18:02:19  2018-05-21 19:07:31
13    2018-05-21 05:07:28  2018-05-21 06:07:51
14    NA                   2018-05-21 13:10:22
15    2018-05-21 11:05:19  2018-05-21 12:17:31
16    2018-05-21 02:27:08  2018-05-21 03:33:54
17    2018-05-21 02:12:01  2018-05-21 03:18:11
18    2018-05-21 11:07:23  2018-05-21 12:21:30
19    2018-05-21 12:31:53  NA
20    2018-05-21 06:19:52  NA

I am trying to replace the entries that are "NA" with the corresponding value from the other column. So for row 4 I want ETime to be the same as the relevant row 4 XTime "2018-05-21 16:14:16" and then row 9 XTime to be "2018-05-21 12:01:12" etc...

Desired output:

                  ETime              XTime
0     2018-05-21 04:48:22  2018-05-21 05:52:45
1     2018-05-21 02:18:20  2018-05-21 03:19:53
2     2018-05-21 11:02:31  2018-05-21 12:17:57
3     2018-05-21 06:08:15  2018-05-21 07:08:12
4     2018-05-21 16:14:16  2018-05-21 16:14:16
5     2018-05-21 03:38:12  2018-05-21 04:39:05
6     2018-05-21 17:43:06  2018-05-21 18:59:38
7     2018-05-21 08:52:32  2018-05-21 08:52:32  
8     2018-05-21 02:27:44  2018-05-21 03:33:08
9     2018-05-21 12:01:12  2018-05-21 12:01:12  
10    2018-05-21 10:21:10  2018-05-21 11:26:45
11    2018-05-21 21:27:38  2018-05-21 21:27:38
12    2018-05-21 18:02:19  2018-05-21 19:07:31
13    2018-05-21 05:07:28  2018-05-21 06:07:51
14    2018-05-21 13:10:22  2018-05-21 13:10:22
15    2018-05-21 11:05:19  2018-05-21 12:17:31
16    2018-05-21 02:27:08  2018-05-21 03:33:54
17    2018-05-21 02:12:01  2018-05-21 03:18:11
18    2018-05-21 11:07:23  2018-05-21 12:21:30
19    2018-05-21 12:31:53  2018-05-21 12:31:53
20    2018-05-21 06:19:52  2018-05-21 06:19:52

I have tried writing a function to try and replace the NA value with a value from another column but am struggling to get it to work for both columns.

Upvotes: 2

Views: 2354

Answers (1)

BENY
BENY

Reputation: 323346

Using fillna

df.ETime.fillna(df.XTime,inplace=True)

df.XTime.fillna(df.ETime,inplace=True)

Upvotes: 5

Related Questions