IMiller
IMiller

Reputation: 51

Python Variable lookup based on dynamic columns per row

I have the following two data frames:

Ticker | Fund  | PB1  | PB2   | PB3   | PB4
KMX    | Bob   | BAML | GS    | MACQ  | HSBC
TEX    | Jon   | JPM  | UBS   |
ARC    | Pat   | JPM  | UBS   | CITI  | WF


Ticker  | Rate  | PB
KMX     |-2     | GS
TEX     |-5     | JPM
TEX     |-3     | UBS 
ARC     |-10    | WF 

I ultimately need to replace the PB in data frame 1 with a rate that is offered by the PB Based on the sample above- the data frame would look like

Ticker | Fund  | PB1  | PB2   | PB3   | PB4
KMX    | Bob   |      | -2    |       | 
TEX    | Jon   | -5   | -3    |
ARC    | Pat   |      |       |       | -10

I have thought about adding additional columns with a rate based on who is in the PB column but I can't figure out the variable nature of the number of PBs per fund.

I tried using a merge but I can't figure out where to go from here.

loadin=Trade_options_final.merge(Total, how='left', on=[])

Upvotes: 2

Views: 50

Answers (1)

BENY
BENY

Reputation: 323306

Good question , you may need melt first then merge then pivot it back

yourdf=df.melt(['Ticker','Fund']).\
          merge(df1.rename(columns={'PB':'value'}),how='left').\
          fillna('').\
          pivot_table(index=['Ticker','Fund'],columns='variable',values='Rate',aggfunc='first').\
          reset_index()
yourdf                                                                                                       
Out[508]: 
variable Ticker Fund PB1 PB2 PB3 PB4
0           ARC  Pat             -10
1           KMX  Bob      -2        
2           TEX  Jon  -5  -3  

Upvotes: 2

Related Questions