Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

rearranging words in the header dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading