Reverse the sequence while keeping pairs of columns in a dataframe

Let’s say my dataframe df has this sequence of columns:

['e', 'f', 'c', 'd', 'a', 'b']

And I want to reverse the sequence while keeping pairs, resulting in this sequence:

['a', 'b', 'c', 'd', 'e', 'f']

If the column names were always the same, I could use this same list above to generate the desired dataframe:

df = df[['a', 'b', 'c', 'd', 'e', 'f']]

But if there can be multiple pairs of columns and without certainty of their names, the only certainty being that the last pair should come first and so on, how to proceed?

>Solution :

You can try:

new_cols = df.columns.to_numpy().reshape(-1,2)[::-1].ravel()

Or since the sorted method is stable, you can reversely sort by the pair order:

n,N = 2,len(df.columns)
df.iloc[:, sorted(range(N), key=lambda x: x//n, reverse=True)]

Leave a Reply