Home > Net >  Pandas data manipulation with date
Pandas data manipulation with date

Time:02-14

I have two df, I want to manipulation the one on the basis of other. My df1 looks like this date format is mm-dd-yyyy

Date col_1 col_2 col_3 = col_2/col_1
01/01/2021 100 110 1.1
02/01/2021 110 110 1
03/01/2021 120 132 1.1
04/01/2021 100 120 1.2

Now my other data frame look like this

Date col_1 col_2
01/01/2021 A 110
01/01/2021 B 110
01/01/2021 C 132
01/01/2021 D 120
02/01/2021 A 110
02/01/2021 B 110
02/01/2021 C 132
03/01/2021 D 120

Now I want to multiply "col_3" of df1 to "col_2" of df2 on date wise. Please help

I tried this

def (df1,df2,ind) #ind is integer for month
    df2['col_2'] = df2['col_2'] * df1['col_3'].iloc(ind-1)
    return df2

my desired output look like

Date col_1 col_2
01/01/2021 A 121
01/01/2021 B 121
01/01/2021 C 145.2
01/01/2021 D 132
02/01/2021 A 110
02/01/2021 B 110
02/01/2021 C 132
03/01/2021 D 132

CodePudding user response:

IIUC, use Date column as index of both dataframes then apply your operation:

df2['col_3'] = df2.set_index('Date')['col_2'] \
                  .mul(df1.set_index('Date').reindex(df2['Date'])['col_3']).values
print(df2)

# Output
         Date col_1  col_2  col_3
0  01/01/2021     A    110  121.0
1  01/01/2021     B    110  121.0
2  01/01/2021     C    132  145.2
3  01/01/2021     D    120  132.0
4  02/01/2021     A    110  110.0
5  02/01/2021     B    110  110.0
6  02/01/2021     C    132  132.0
7  03/01/2021     D    120  132.0
  • Related