简体   繁体   中英

Double Constrained Loop in Python

I have an issue which is rather simple in theory. I just can't seem to wrap my head around a solution. I have 2 Pandas dataframes.

Dataframe A:

Date           Currency    
-------------------------
2019-11-29     EUR
2019-11-29     USD
.              GBP
.              .
.              .
2019-10-31

Dataframe B:

Date          Currency   Conversion
-----------------------------------
2019-11-29    USD        0.79
2019-11-29    GBP        1.23
2019-11-29    CHF        1.41
2019-11-28    USD        .
.
.
.
2019-10-31   USD         .
2019-10-31   GBP
2019-10-31   USD

I essentially have a long list of trades in Dataframe A, around 5-15 a day. The instruments are bought in different currencies, which all should be denominated in euros. I wrote a piece from SQL that retrieves the conversion rates (from currency XX to EUR) at all dates in the period.

Now I need to add a column to dataframe A:

IF DataframeA[Date] = DataframeB[Date] AND DataframeA[Currency] = DataframeB[Currency]

then the corresponding conversion rate should be added.

The IF statement in itself I can do, but I can't seem to iterate and update as my script runs. Any ideas?

Best Patrick

DataframeA = pd.merge(DataframeA, DataFrameB, on=['Date', 'Currency'])

by default it's inner join. you can choose to modify that accordingly by using the option Ex: how = 'outer' in the merge command. Further, drop or keep the column as you like or choose to add suffix or prefix in the common columns coming from two dataframes. Read the doc

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