I asked the same question for R and I obtained the answer, I hope to obtain it for Python too.
I have a dataset that looks like this:
tenor delivery_window
<chr> <chr>
1 month Nov 22
2 quarter Jan 22
3 year Cal 24
4 year Cal 22
5 month Feb 22
6 quarter Jan 21
7 month Sep 22
8 quarter Jan 21
9 month Jun 21
10 month Aug 21
And which I want to turn into something like this:
tenor delivery_window new_tenor
<chr> <chr> <chr>
1 month Nov 22 Nov 22
2 quarter Jan 22 Q1 22
3 year Cal 24 Cal 24
4 year Cal 22 Cal 22
5 month Feb 22 Feb 22
6 quarter Jan 21 Q1 21
7 month Sep 22 Sep 22
8 quarter Jan 21 Q1 21
9 month Jun 21 Jun 21
10 month Aug 21 Aug 21
That is, if the tenor is quarter, I want to show only the quarter corresponding to the delivery window, not the month. Monthly and Yearly tenors can remain as they are.
The new_tenor should be Q1 YY for months from Jan YY to Mar YY, Q2 YY for months from Apr YY to Jun YY, Q3 YY for months from Jul YY to Sep YY, and Q4 YY for months from Oct YY to Dec YY.
Can someone please help me again? Thank you in advance.
CodePudding user response:
I think this is what you're looking for:
def ConvtoQuarter(tenor, delivery):
if tenor == "quarter":
if delivery[:3] in ['Jan', 'Feb', 'Mar']:
return "Q1 " delivery[-2:]
elif delivery[:3] in ['Apr', 'May', 'Jun']:
return "Q2 " delivery[-2:]
elif delivery[:3] in ['Jul', 'Aug', 'Sep']:
return "Q3 " delivery[-2:]
elif delivery[:3] in ['Oct', 'Nov', 'Dec']:
return "Q4 " delivery[-2:]
else:
return delivery
df = pd.DataFrame({"tenor":['month', 'quarter', 'year', 'year', 'month', 'quarter'],
"delivery":['Nov 22', 'Jan 22', 'Cal 22', 'Cal 22', 'Feb 22', 'Jan 21']})
df['NewTenor'] = df.apply(lambda x: ConvtoQuarter(x['tenor'], x['delivery']), axis=1)
df
Output:
tenor delivery NewTenor
0 month Nov 22 Nov 22
1 quarter Jan 22 Q1 22
2 year Cal 22 Cal 22
3 year Cal 22 Cal 22
4 month Feb 22 Feb 22
5 quarter Jan 21 Q1 21
