Map Series to DataFrame while disregarding year

Viewed 35

I have a DataFrame and a Series, the DataFrame has data from 1983 to 2016 and the Series has only 1 year of data (and the year doesn't matter). I want to add a new column to the DataFrame with the data from the Series, except (since I have only 1 year in the Series) I would like to ignore the year of the Series. So, Jan 1st 00:00 in the series should map to Jan 1st 00:00 for all 34 years in the DataFrame. Does anyone know a nice Panda way to do this without using .apply?

2 Answers

If working with datetimes in indices use Index.map with same format od DatetimeIndexes:

s.index = pd.to_datetime(s.index)
df.index = pd.to_datetime(df.index)
df['new'] = df.index.strftime('%m-%d %H:%M').map(s.rename(index=lambda x: x.strftime('%m-%d %H:%M')))

Thank you, Jezrael!

In the end I went for this solution, it's a bit more declarative in my opinion. I'm not sure which method is more performative, but I have only a few thousand lines, so in the end either way should work just fine. :)

s.index = pd.to_datetime(s.index)
df.index = pd.to_datetime(df.index)
df['new'] = df.index.to_series().apply(lambda timestamp: s.loc[timestamp.replace(year=2030)])
Related