简体   繁体   中英

How to add a column that based on the different value for every row conducts excel type “INDEX, MATCH, MATCH” search from another dataframe?

I am trying to add a column called "Yield to Worst" and that for every row it use the "Ticker" value for that row and conducts a INDEX, MATCH, MATCH to another dataframe to find the value Yield to Worst for a particular ticker. The dataframes are below "Tickers" and "Funds_Data". The desired output as well.

Tickers Dataframe

Index   Tickers
0   IEF US Equity
1   JNK US Equity
2   HYG US Equity
3   LQD US Equity

Funds_Data Dataframe

         JNK US Equity  HYG US Equity   LQD US Equity   IEF US Equity
AUM      9560           16313           31525           13169
Duration 3.6            3.3             8.8             7.4
1-Mth    1.17           0.94            0.85            0.11
3-Mth    4.11           3.59            3.38            1.93
YTD      9.52           8.66            6.61            2.21
Yield    6.46           6.23            4.08            2.49

Desired Output

Index   Tickers    Yield
0   IEF US Equity   2.49
1   JNK US Equity   6.46
2   HYG US Equity   6.23
3   LQD US Equity   4.08

Attempted Code

for ticker in range (0, len(Tickers)):
    Yield = pd.DataFrame(funds_data.loc['Yield to Worst', ticker])
Tickers['Yield'] = Yield

Thank you for all the help

You can merge tickers with funds_data taking the Yield row:

tickers.merge(funds_data.loc['Yield'],
              how='left', left_on='Tickers', right_index=True)

Output:

             Tickers  Yield
Index                      
0      JNK US Equity   6.46
1      HYG US Equity   6.23
2      LQD US Equity   4.08
3      IEF US Equity   2.49
5      MBB US Equity    NaN

PS There's no data for "MBB US Equity" in your sample funds_data , so it comes out as NaN

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