我对R
问了同样的问题,我得到了答案,我希望Python
也能得到答案。
我有一个看起来像这样的数据集:
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
我想把它变成这样:
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
也就是说,如果tenor
是quarter
,我只想显示delivery window
对应的季度,而不是月份。月号和年号可以保持不变。
Jan YY
~Mar YY
月份的new_tenor
为Q1 YY
,Apr YY
~Jun YY
月份的Q2 YY
,Jul YY
~Sep YY
月份的Q3 YY
,Oct YY
~Dec YY
月份的Q4 YY
。
我想这就是你要找的:
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
输出:
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