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

How to reorder columns if the columns have the same part name

I want to reorder columns name if the columns have the same part name. Sample as below:

import pandas as pd

df = pd.DataFrame({'Branch': ['Hanoi'], '20241201_Candy': [3], '20241202_Candy': [4], '20241203_Candy': [5],
                  '20241201_Candle': [3], '20241202_Candle': [4], '20241203_Candle': [5],
                  '20241201_Biscuit': [3], '20241202_Biscuit': [4], '20241203_Biscuit': [5]})

df

Below is my Expected Ouput:

df2 = pd.DataFrame({'Branch': ['Hanoi'], 
                    '20241201_Biscuit': [3], '20241201_Candle': [3], '20241201_Candy': [3], 
                    '20241202_Biscuit': [4], '20241202_Candle': [4], '20241202_Candy': [4],
                    '20241203_Biscuit': [5], '20241203_Candle': [5], '20241203_Candy': [5]})

So I want to auto reorder dataframe if it has same date.

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

>Solution :

You can use df.reindex, single out column 'Branch' and apply sorted to the remainder, df.columns[1:]:

out = df.reindex(['Branch'] + sorted(df.columns[1:]), axis=1)

out.equals(df2)
# True

Or directly:

out2 = df[['Branch'] + sorted(df.columns[1:])]

out2.equals(df2)
# 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