pythonpandas

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]})

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.


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