I have a dataframe:
df = pd.DataFrame({
'FY18Q1': [ 1500, 1200, 950, 2200],
'FY18Q2': [ 2340, 1234, 2000, 1230],
'FY18Q3': [2130, 2200, 2190, 2210],
'FY18YearTotal': [1000, 1900, 1500, 1800]})
I wish to re-arrange the order of the header. I want to the header to read ‘1Q18’ where it does ‘FY181Q’ and ‘FY18’ where it reads ‘FY18YearTotal’
I can drop the ‘FY’ and ‘YearTotal’ by:
df.columns = df.columns.str.replace(r"(|FY|\.)", "")
df.columns = df.columns.str.replace(r"(|YearTotal|\.)", "")
But it does not get me to:
df = pd.DataFrame({
'1Q18': [ 1500, 1200, 950, 2200],
'2Q18': [ 2340, 1234, 2000, 1230],
'3Q18': [2130, 2200, 2190, 2210],
'FY18': [1000, 1900, 1500, 1800]})
>Solution :
You can simply chain two calls to str.replace
here:
df.columns = df.columns.str.replace(r'^FY(\d+)Q(\d+)', r'\2Q\1', regex=True)
.str.replace(r'YearTotal$', r'', regex=True)