Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate DatetimeIndex objects in pandas?

Let's say I have 3 pandas DatetimeIndex objects:

import pandas as pd

idx1 = pd.date_range('2019-01-01 00:00:00', '2019-01-01 01:00:00', freq='5T')
idx2 = pd.date_range('2019-01-01 02:00:00', '2019-01-01 03:00:00', freq='5T')
idx3 = pd.date_range('2019-01-02 00:00:00', '2019-01-02 01:00:00', freq='5T')

How can I combine them into a single index?

The roundabout way I do is by first converting them to series, then using pandas.concat function to combine them, and then converting the series back to DatetimeIndex:

# This works, but requires type conversions to and from
# intermediate series objects:
combined = pd.concat([idx1.to_series(), idx2.to_series(), idx3.to_series()])
idx = pd.DatetimeIndex(combined.values)

Is there a direct way to combine indices in pandas?

like image 613
hazrmard Avatar asked Dec 14 '22 12:12

hazrmard


1 Answers

Try the clause 'union'.

combined = idx1.union(idx2).union(idx3)
like image 89
jose_bacoy Avatar answered Jan 05 '23 19:01

jose_bacoy