Search code examples
pythonpandassplice

Splicing Together Series in Pandas


I have two series representing the same underlying data, but one is quarterly (with more backhistory) and the second is monthly. I would like to splice the monthly data back with quarterly data such that I get back a single series combining the two. What is the most "pandas" way of doing this? I have already resampled the quarterly data to monthly.

Example Code:

ts1 = pd.Series(data=1, index=pd.DatetimeIndex(freq="Q", start="2000-03-31", end="2016-03-31")).resample("M").last().ffill()
ts2 = pd.Series(data=2, index=pd.DatetimeIndex(freq="M", start="2012-01-31", end="2016-03-31"))

I would like the result to be ts1 before 2012-01-31 and ts2 after.


Solution

  • For this specific case, you can use combine_first:

    ts2.combine_first(ts1)
    

    This will take the values from ts2 if both series contain the same indices, and from ts1 if only ts1 has that index.

    You can also use pd.concat:

    pd.concat((ts1[:'20120130'], ts2))
    

    pd.concat((ts1[:'20120130'], ts2)).equals(ts2.combine_first(ts1))
    Out: True