I have two Multiindex dataframes, namely, panel1 and panel2: both have the same level 0 index-the dates, but different level 1 index; see sample code below:
# panel1:
idx1 = pd.MultiIndex.from_product([['2017-05-02', '2017-05-03', '2017-05-04'],['id1', 'id2', 'id3']],names=['Dates', 'id'])
panel1=pd.DataFrame(np.random.randn(9,2), index=idx1,columns=['ytm','mat'])
# panel2:
idx2 = pd.MultiIndex.from_product([['2017-05-02', '2017-05-03', '2017-05-04'],['0.5', '1.5', '2.5']],names=['Dates', 'yr'])
panel2=pd.DataFrame(np.random.randn(9), index=idx2,columns=['curve'])
I want to loop over the two panels by the Dates (level 0 index). So for each day (e.g. '2017-05-02'), I search the mat of each id/row (of panel1) in the yr column (of panel2), if there is a match, I want to get the corresponding curve values (of panel2) and add it as a new column (named CDB) in panel1.
My current code as following:
group1=panel1.groupby(level=0)
group2=panel2.groupby(level=0)
lst=[]
for ytm in group1: # loop over each day
for yr in group2: # loop over each day
df_ytm=ytm[1] # get df of id, yt & mat
df_ytm=df_ytm.assign(CDB=np.nan) # add a col of nan, later will be replaced by matched curve values
df_curve=yr[1].reset_index() # need get rid of index to match yr with t_mat
df_curve.yr=df_curve.yr.astype(float)
for i in range(df_ytm.shape[0]): # loop over each row
if (df_ytm.iloc[i,1]==df_curve.yr).any()==True: # search if each 'mat' value in 'yr' column
df_ytm.iloc[i,2]=df_curve[df_curve.yr.isin([df_ytm.t_mat[i]])].curve.values # if matched, set 'CDB' as curve value
lst.append(df_ytm) # need get modified 'df_ytm' (with matched 'CDB')
The code works as I tried with a small sample, but I have a huge panel 1 (sized 800 days times 10000 ids) and big panel 2 as well. So the code has been running for more than 24 hours.
I wonder how could I rewrite the code (use possible vectorization) to speed it up?
Any comments would be much appreciated!