BeardedDork
BeardedDork

Reputation: 160

Reindexing Pandas Dataframe with specific datetime indexes

I have a simple question best described with an example. I am trying to render output_df based on current_df and parent_df.

current_df: simple time series df with datetime index

Index                            Val
'10-1-2010 08:00:00'              1.23
'10-1-2010 09:00:00'              1.3
'10-1-2010 10:00:00'               1.43

parent_df: another simple time series df

Index                            Val
'10-1-2010 07:00:00'              0.23
'10-1-2010 08:00:00'              1.23
'10-1-2010 09:00:00'              1.3
'10-1-2010 10:00:00'               1.43
'10-1-2010 11:00:00'              2.23

The output_df should:

  1. contain index of parent_df
  2. contain val of 0 if index not in current_df
Index                             Val
'10-1-2010 07:00:00'              0
'10-1-2010 08:00:00'              1.23
'10-1-2010 09:00:00'              1.3
'10-1-2010 10:00:00'               1.43
'10-1-2010 11:00:00'                0

This should be an easy task - I'm just blanking.

Cheers.

Upvotes: 2

Views: 410

Answers (3)

lobetdenherrn
lobetdenherrn

Reputation: 313

I think this code snippet will help you.

# copy the dataframe
output_df = parent_df

# use negated .isin() search to find the indices that are not in current_df
# and replace them with zero
output_df.loc[~output_df['Index'].isin(current_df['Index'])] = 0

Upvotes: 1

Dev Khadka
Dev Khadka

Reputation: 5451

you can do it using merge like below

parent_df[["Index"]].merge(current_df, on="Index", how="left").fillna(0)

Upvotes: 1

Andy L.
Andy L.

Reputation: 25249

I think it is the functionality of reindex

output_df = current_df.reindex(parent_df.index, fill_value=0)

Upvotes: 1

Related Questions