简体   繁体   中英

Python pandas: multiply 2 columns of 2 dataframes with different datetime index

I have 2 dataframes UsdBrlDSlice and indexesM . The first is in daily basis, and has and index in yyyy-mm-dd format, and the second is in monthly basis, and has an index in yyyy-mm format.

Example of UsdBrlDSlice :

              USDBRL
date                
1994-01-03  331.2200
1994-01-04  336.4900
1994-01-05  341.8300
1994-01-06  347.2350
1994-01-07  352.7300
             ...
2020-10-05    5.6299
2020-10-06    5.5205
2020-10-07    5.6018
2020-10-08    5.6200
2020-10-09    5.5393

I need to insert a new column in UsdBrlDSlice , multiplying it´s value USDBRL with a specific column in indexesM['c'] , but matching the correct month of both indexes.

Something like excel´s vlookup multiplication. Thanks.

我解决了 1) 在第一个数据框中创建一个新的ym列,然后 2) 应用 map() 函数:

  1. UsdBrlDSlice['y-m'] = UsdBrlDSlice.index.to_period('M')

  2. UsdBrlDSlice['new col'] = UsdBrlDSlice['USDBRL'] * UsdBrlDSlice['y-m'].map(indexesM.set_index(indexesM.index)['c'])

UsdBrlDSliceTmp = UsdBrlDSlice.copy()
UsdBrlDSliceTmp['date_col'] = UsdBrlDSliceTmp.index.values
indexesMTmp = indexesM.copy()
indexesMTmp['date_col'] = indexesMTmp.index.values
UsdBrlDSliceTmp['month'] = UsdBrlDSliceTmp['date_col'].apply(lambda x: x.month)
indexesMTmp['month'] = indexesMTmp['date_col'].apply(lambda x: x.month)

UsdBrlDSliceTmp = UsdBrlDSliceTmp.merge(indexesMTmp, on='month', how='left')
UsdBrlDSliceTmp['target'] = UsdBrlDSliceTmp['USDBRL']*UsdBrlDSliceTmp['c']
UsdBrlDSlice['new_col'] = UsdBrlDSliceTmp['target']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM