You have a pandas dataframe and you do not like the ordering of the columns. You want to change the orders of the columns.
Let’s first read a dataset to work with.
df = pd.read_csv("https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv") df.head()
Let’s say that you want rearrange the Gender, Marital Status and Age columns after the Type of Customer columns instead of at last.
To change the order of the columns, first you need to get the name of the columns.
# get column names cols = df.columns.tolist() cols
Now, you need to rearrange the column names the way you like it.
cols = cols[:2] + cols[5:] + cols[2:5] cols
Now, all you have to do is select the data from the dataframe based on this rearranged column names and assign it back to the dataframe like shown below.
# rearrange the column names df = df[cols] df.head()
If you want you can also manually rearrange the column names instead of list slicing method that we used. It completely up to you. The goal is to rearrange the column names the way you want it.