Skip to content

Instantly share code, notes, and snippets.

@berkorbay
Created April 18, 2022 14:37
Show Gist options
  • Save berkorbay/df825d4d3cdaa485266bec268eb6931e to your computer and use it in GitHub Desktop.
Save berkorbay/df825d4d3cdaa485266bec268eb6931e to your computer and use it in GitHub Desktop.
Small function to reorder columns using Pandas. This is a quick and dirty approach. I'm pretty sure there are better alternatives.
import pandas as pd
def pd_reorder_cols(df, d):
"""
Reorders the position of columns with the given specs dictionary.
"""
cl = list(df.columns)
for k1, v1 in d.items():
k1_ix = cl.index(k1)
cl.pop(k1_ix)
for k2, v2 in v1.items():
if k2 == "before":
ix = cl.index(v2)
elif k2 == "after":
ix = cl.index(v2) + 1
elif k2 == "position":
if v2 == "start":
ix = 0
elif v2 == "end":
ix = len(cl)
else:
ix = v2
else:
raise Exception("Command " + k2 + " is not valid. Please use before, after or position.")
cl.insert(ix, k1)
return df[cl]
if __name__ == "__main__":
df = pd.DataFrame(data={"A": [0, 1, 2], "B": ["x", "y", "z"], "C": ["f6", "g7", "h8"]})
print(pd_reorder(df, {"A": {"position": "end"}, "B": {"before": "A"}, "C": {"position": 1}}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment