Python 选择从比较数据帧列和列表中派生的数据帧索引
考虑到下面的Python 选择从比较数据帧列和列表中派生的数据帧索引,python,pandas,Python,Pandas,考虑到下面的仪器\u ticker数据帧和ticker列表: import pandas as pd import numpy as np 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'], 'Instrument': ['EWZ', 'HSI',
仪器\u ticker
数据帧和ticker
列表:
import pandas as pd
import numpy as np
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'],
'Instrument': ['EWZ', 'HSI', 'TLT', 'EWZ'],
'Maturity Label': ['MAI 20 D29', 'DEC 20 D30', 'JUN 20 D19', 'MAY 20 D29'],
'Strike': [27, 24800, 225, 29],
'Payout': ['P', 'C', 'C', 'P'],
'Maturity': ['29/05/2020', '12/30/2020', '19/06/2020', '29/05/2020'],
'Market': ['US NYSE', 'US NYSE', 'HK HKSE', 'US NYSE']})
stk_off['Reduced_Ticker'] = stk_off['Ticker'].apply(lambda a :" ".join(a.split(" ", 2)[:2]))
instrument_ticker = stk_off[['Instrument','Reduced_Ticker']].groupby(['Instrument']).agg(list)
instrument_ticker['Reduced_Ticker'] = instrument_ticker['Reduced_Ticker'].apply(lambda x: pd.unique(x))
ticker = ['EWZ US 05/29/20 C31','HSI US 12/30/20 C24900']
我进行拆分以选择从每行的此操作中获得的每个值的第一项:
tickers_reduced = [t.split()[0] for t in tickers]
现在,我如何获得仪器\u ticker
的索引,其中减少的\u ticker
包含一个减少的项目?我需要将其保存在列表中,如下所示(预期输出):
通过检查
Reduced\u Ticker
的第一个拆分项,然后获取所选行的索引,选择所需内容:
selection = (
instrument_ticker
.explode('Reduced_Ticker')
['Reduced_Ticker']
.apply(lambda x : x.split()[0] in tickers_reduced)
)
instrument = instrument_ticker.loc[selection].index.to_list()
selection = (
instrument_ticker
.explode('Reduced_Ticker')
['Reduced_Ticker']
.apply(lambda x : x.split()[0] in tickers_reduced)
)
instrument = instrument_ticker.loc[selection].index.to_list()