I have been trying a code using multiple if statement but this process seems to take more execution time if the number of observations are many. Basically the code checks the value in two columns (rate and rate_tenor) and if condition matches in both the column, then that needs to be replaced by certain value (for e.g. if rate = 'RATE1' and rate_tenor = 1 MONTH
, then replace the rate value at that index with '1 MO RATE1'
). I have written the code using lots of "if" statement but I am looking for more efficient way that executes faster.
There can be many values in rate column, but only those needs to be replaced that have value either RATE1
or RATE2
and particular tenor value(1, 3, 6 or 12 month).
This is the code I wrote:
if 'column1' in columns_in_dataframe:
tenor = df['column1']
rate = df['column2']
# Iterate through each value
for idx, val in enumerate(rate):
if val == 'RATE1':
if tenor[idx] == '1 MONTH':
tape.loc[idx, 'column2'] = '1 MO RATE1'
elif tenor[idx] == '3 MONTH':
tape.loc[idx, 'column2'] = '3 MO RATE1'
elif tenor[idx] == '6 MONTH':
tape.loc[idx, 'column2'] = '6 MO RATE1'
elif tenor[idx] == '12 MONTH':
tape.loc[idx, 'column2'] = '12 MO RATE1'
if val == 'RATE2':
if tenor[idx] == '1 MONTH']:
tape.loc[idx, 'column2'] = '1 MO RATE2'
elif tenor[idx] == '3 MONTH']:
tape.loc[idx, 'column2'] = '3 MO RATE2'
elif tenor[idx] == '6 MONTH']:
tape.loc[idx, 'column2'] = '6 MO RATE2'
elif tenor[idx] == '12 MONTH']:
tape.loc[idx, 'column2'] = '12 MO RATE2'