Home > Net >  Pandas - left outer joins based on indices
Pandas - left outer joins based on indices

Time:10-04

I have a pandas dataframe like this. I will call this D1:

enter image description here

The dates here are not continuous. I have another dataframe D2 whose index contains all the dates for which I need rows in the above dataset.

I need to create a dataframe D3 such that:

  1. It contains a record for each date in D2
  2. If a row is present for a date in D1, then that record should be reproduced. Otherwise, D3 should contain a record for the date with NaNs for all fields

How do I do this? Is it possible to do this without joins?

CodePudding user response:

Create DatetimeIndexes in both DataFrames if necessary and then use DataFrame.reindex:

DF1.index = pd.to_datetime(DF1.index)
DF2.index = pd.to_datetime(DF2.index)

DF3 = DF1.reindex(DF2.index)
  • Related