Reputation: 35
I am a complete newbie in Python - for doing a procedural calculation of interests within a mortgage plan i need to calculate with dates. There is a date array for the payments and another date array for summing up the interests.
I am completely stuck with merging the two date arrays - i would need only one merged array with sorted dates. I read through different approaches (DataFrames, Joins, Merges) but couldn't find any solution.
import pandas as pd
date_range_1 = pd.date_range(start='1/1/2019', periods=12,freq='M')
date_range_2 = pd.date_range(start='31/3/2019',periods=4,freq='3M')
Question-1: How to join these 2 arrays
Question-2: How to sort by date
Output should be:
'1/1/2019'
'1/2/2019'
'1/3/2019'
'31/3/2019'
'1/4/2019'
'1/5/2019'
'1/6/2019'
'30/6/2019'
...
Edit: Full input + solution:
import pandas as pd
dates_1= pd.date_range('2018-01-01','2020-01-01' , freq='1M')-pd.offsets.MonthBegin(1)
dates_2= pd.date_range('2018-03-31','2020-03-31' , freq='3M')-pd.offsets.MonthEnd(0)
Union_dates = pd.Series(sorted(dates_1.union(dates_2)))
print(Union_dates)
Upvotes: 2
Views: 922
Reputation: 544
You can append
one range to another and then sort_values
.
import pandas as pd
date_range_1 = pd.date_range(start='1/1/2019', periods=12, freq='MS')
date_range_2 = pd.date_range(start='31/3/2019', periods=4, freq='3M')
date_range_1.append(date_range_2).sort_values()
DatetimeIndex(['2019-01-01', '2019-02-01', '2019-03-01', '2019-03-31',
'2019-04-01', '2019-05-01', '2019-06-01', '2019-06-30',
'2019-07-01', '2019-08-01', '2019-09-01', '2019-09-30',
'2019-10-01', '2019-11-01', '2019-12-01', '2019-12-31'],
dtype='datetime64[ns]', freq=None)
Upvotes: 2
Reputation: 75080
IIUC, you need Index.union
:
pd.Series(sorted(date_range_1.union(date_range_2)))
0 2019-01-31
1 2019-02-28
2 2019-03-31
3 2019-04-30
4 2019-05-31
5 2019-06-30
6 2019-07-31
7 2019-08-31
8 2019-09-30
9 2019-10-31
10 2019-11-30
11 2019-12-31
dtype: datetime64[ns]
Upvotes: 3