我有一个看起来像这样的数据框:
Strike Right Price
4000 CE 45
4000 PE 55
4100 CE 30
4100 PE 60
我想创建一个 df ,其输出为
4000PE 4100PE
4000CE 100 105
4100CE 85 90
你能指导我如何创建这个吗 np.add.outer 更快吗?还是 numpy 的广播更快?
您可以使用 numpy 广播:
mux = pd.MultiIndex.from_frame(df[['Strike','Right']])
a = df['Price'].to_numpy()
out = pd.DataFrame(a + a[:, None], index=mux, columns=mux)
print (out)
Strike 4000 4100
Right CE PE CE PE
Strike Right
4000 CE 90 100 75 105
PE 100 110 85 115
4100 CE 75 85 60 90
PE 105 115 90 120
对于选择
CE and
PE` 切片,请使用:
idx = pd.IndexSlice
out1 = out.loc[idx[:, 'CE'], idx[:, 'PE']]
out1.index = out1.index.map(lambda x: f'{x[0]}{x[1]}')
out1.columns = out1.columns.map(lambda x: f'{x[0]}{x[1]}')
print (out1)
4000PE 4100PE
4000CE 100 105
4100CE 85 90