Skip to content
Advertisement

move column in pandas dataframe

I have the following dataframe:

JavaScript

How can I move columns b and x such that they are the last 2 columns in the dataframe? I would like to specify b and x by name, but not the other columns.

Advertisement

Answer

You can rearrange columns directly by specifying their order:

JavaScript

In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.

JavaScript

To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement