0

I couldn't find another thread with the exact same question, so I hope, I'm not opening too much of the same old one.

I'm just learning to work with pandas and date time objects and I'm looking to create a big DatetimeIndex object with a range of dates and after that, calculate the difference set between the big one and several smaller ones, but I'm running into an error here:

range1 = pd.date_range(start="2015-01-01", end="2015-02-01")
range2 = pd.date_range(start="2015-01-03", end="2015-01-07")
range3 = pd.date_range(start="2015-01-13", end="2015-01-20")
range = range1 - range2 - range3
print(range)

ValueError: cannot add indices of unequal length

I was hoping the above code would give me the date range between the given points minus the dates of the following ranges, but I'm stuck here. Could someone explain, please?

CptSnuggles
  • 137
  • 1
  • 3
  • 11

1 Answers1

1

Use Index.difference, also dont use range like variable name, because builtins (python code word):

range1 = pd.date_range(start="2015-01-01", end="2015-02-01")
range2 = pd.date_range(start="2015-01-03", end="2015-01-07")
range3 = pd.date_range(start="2015-01-13", end="2015-01-20")
r = range1.difference(range2).difference(range3)
print(r)
DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-08', '2015-01-09',
               '2015-01-10', '2015-01-11', '2015-01-12', '2015-01-21',
               '2015-01-22', '2015-01-23', '2015-01-24', '2015-01-25',
               '2015-01-26', '2015-01-27', '2015-01-28', '2015-01-29',
               '2015-01-30', '2015-01-31', '2015-02-01'],
              dtype='datetime64[ns]', freq=None)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252