Considering the instrument_ticker
dataframe and tickers
list below:
JavaScript
x
18
18
1
import pandas as pd
2
import numpy as np
3
4
stk_off = pd.DataFrame({'Ticker': ['EWZ US 05/29/20 P27', 'HSI US 12/30/20 C24800', 'TLT US 06/19/20 C225', 'EWZ US 05/29/20 P29'],
5
'Instrument': ['EWZ', 'HSI', 'TLT', 'EWZ'],
6
'Maturity Label': ['MAI 20 D29', 'DEC 20 D30', 'JUN 20 D19', 'MAY 20 D29'],
7
'Strike': [27, 24800, 225, 29],
8
'Payout': ['P', 'C', 'C', 'P'],
9
'Maturity': ['29/05/2020', '12/30/2020', '19/06/2020', '29/05/2020'],
10
'Market': ['US NYSE', 'US NYSE', 'HK HKSE', 'US NYSE']})
11
12
stk_off['Reduced_Ticker'] = stk_off['Ticker'].apply(lambda a :" ".join(a.split(" ", 2)[:2]))
13
14
instrument_ticker = stk_off[['Instrument','Reduced_Ticker']].groupby(['Instrument']).agg(list)
15
instrument_ticker['Reduced_Ticker'] = instrument_ticker['Reduced_Ticker'].apply(lambda x: pd.unique(x))
16
17
ticker = ['EWZ US 05/29/20 C31','HSI US 12/30/20 C24900']
18
I do a split to select the first item of each value obtained from this operation of each line:
JavaScript
1
2
1
tickers_reduced = [t.split()[0] for t in tickers]
2
Now, how can I get the index of instrument_ticker
where Reduced_Ticker
contains a ticker_reduced item? I need to save this in a list, like the following (expected output):
JavaScript
1
2
1
instrument = ['EWZ', 'HSI']
2
Advertisement
Answer
Select what you require by checking the first split term of Reduced_Ticker
, followed by obtaining the index of the selected rows:
JavaScript
1
9
1
selection = (
2
instrument_ticker
3
.explode('Reduced_Ticker')
4
['Reduced_Ticker']
5
.apply(lambda x : x.split()[0] in tickers_reduced)
6
)
7
8
instrument = instrument_ticker.loc[selection].index.to_list()
9