M.E.
M.E.

Reputation: 5496

Merge two columns in Pandas

I have the following Pandas DataFrame:

     date                     at        weight  status    buy_ts               sell_ts
---  -------------------  ------  ------------  --------  -------------------  -------------------
  0  2010-01-03 00:00:00  1.4286             7  buy       2010-01-04 01:47:00  nan
  1  2010-01-03 00:00:00  1.4288             7  buy       2010-01-04 00:00:00  nan
  2  2010-01-03 00:00:00  1.4289             7  buy       2010-01-04 00:00:00  nan
  3  2010-01-04 00:00:00  1.442             25  buy       2010-01-05 00:00:00  nan
  4  2010-01-05 00:00:00  1.4422            15  sell      nan                  2010-01-06 14:03:00
  5  2010-01-05 00:00:00  1.4423            15  sell      nan                  2010-01-06 14:03:00
  6  2010-01-05 00:00:00  1.4424            15  sell      nan                  2010-01-06 14:03:00
  7  2010-01-06 00:00:00  1.4403            18  sell      nan                  2010-01-07 00:04:00
  8  2010-01-06 00:00:00  1.4404            18  sell      nan                  2010-01-07 00:05:00
  9  2010-01-06 00:00:00  1.4405            18  sell      nan                  2010-01-08 08:54:00
 10  2010-01-07 00:00:00  1.4313            26  buy       2010-01-08 00:07:00  nan
 11  2010-01-07 00:00:00  1.4314            26  buy       2010-01-08 00:07:00  nan
 12  2010-01-07 00:00:00  1.4316            26  sell      nan                  2010-01-08 00:10:00

buy_ts and sell_ts contains a Python datetime.datetime object

I would like to create a new column called merged_ts which contains the datetime.dateime object from buy_ts or sell_ts (when one column has value the other is always nan so it is not possible that both columns are populated).

Upvotes: 0

Views: 65

Answers (1)

Code Different
Code Different

Reputation: 93151

Use combine_first:

df['merged'] = df['buy_ts'].combine_first(df['sell_ts'])

Upvotes: 1

Related Questions