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

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:

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 = 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()
print(df[new_cols])

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