I have a complex issue I cannot figure out. I posted a question about it the other day but did not get an answer.
Here is a sample of my dataframe:
df = pd.DataFrame({
'Type': ['EO', 'EO', 'BS', 'BS', 'BS', 'EU', 'EU', 'EU', 'EU', 'SW', 'SW', 'SW', 'SW'],
'B/S': ['Sell', 'Sell', 'Buy', 'Buy', 'Buy', 'Buy', 'Buy', 'Sell', 'Buy', 'Sell', 'Buy', 'Buy', 'Buy'],
'Put/Call': ['Put', 'Put', '', '', '', 'Call', 'Call', 'Call', 'Call', '', '', '', ''],
'StrikePrice': [35, 35, np.nan, np.nan, np.nan, 6, 6, 8, 6, np.nan, np.nan, np.nan, np.nan],
'FixedPrice': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 5, 4, 4, 7],
'FloatPrice': [1, 0.5, np.nan, np.nan, np.nan, 2, 3, 5, 6, 1, 2, 7, 9],
'Fixed Spread': [np.nan, np.nan, np.nan, 10, 20, 30, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
'Float Spread': [np.nan, np.nan, np.nan, 35, 45, 55, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
'Prem Price': [2, 2, np.nan, np.nan, np.nan, 1, 1, 1, 1, np.nan, np.nan, np.nan, np.nan],
'MTM Unrld PV (n)': [-10000, -1, 400000, 1000000, 600000, np.nan, 100000, 28000, np.nan, 56000, 296000, 209000, 207000],
'MTM Realized (n)': [np.nan, np.nan, np.nan, np.nan, np.nan, 74000, np.nan, np.nan, 148000, np.nan, np.nan, np.nan, np.nan]
})
I am reading data from other files. This dataframe needs to be transformed to match the columns of the other data. The columns of the other data that need to be emulated are called ‘FixedPriceStrike’, ‘Price’, and ‘MTMValue’. For this data, I need to shift values between columns depending on the value in column ‘Type’. It is noteworthy to say, there can be an infinite amount of Types but these are the ones I have encountered up to now.
For Instance:
if Type = ‘EO’
I need to take the values from the ‘prem price’ column as my ‘FixedPriceStrike’ and the values from ‘FloatPrice’ column as my ‘Price’
if ‘Type = ‘BS’
I need to take the values from the ‘Fixed Spread’ column as my ‘FixedPriceStrike’ and the values from ‘Float Spread’ column as my ‘Price’
if ‘Type = ‘EU’
I need to take the values from the ‘prem price’ column as my ‘FixedPriceStrike’ and the values from ‘FloatPrice’ column as my ‘Price’ and I need to check if the ‘MTm Unrld PV (n)’ is empty then use the ‘MTM Realized (n) -> ‘MTm Unrld PV (n)’ if it is empty
if ‘Type = ‘SW’
I need to take the values from the ‘FixedPrice’ column as my ‘FixedPriceStrike’ and the values from ‘FloatPrice’ column as my ‘Price’
My original solution only worked for one different case because that was all I needed to handle, but my requirements have changed immensely:
df = df.mask(df['Put/Call'].eq('Put'), df.assign(**{'Fixed Spread': df['Prem Price'].values, 'Float Spread': df['FloatPrice'].values}))
I was moving the correct values to one column then I would rename them to the correct names I needed. Now that I have multiple cases I need to handle, I am unsure how to go about it correctly the pythonic way.
I hope that makes sense, any suggestions would help.