I have the following dataframe:
a b x y
0 1 2 3 -1
1 2 4 6 -2
2 3 6 9 -3
3 4 8 12 -4
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.
You can rearrange columns directly by specifying their order:
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.
To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:
An alternative, more generic method;
This function will reorder your columns without losing data. Any omitted columns remain in the center of the data set:
Example usage:
To assign to your dataframe, use:
You can use
pd.Index.difference
withnp.hstack
, thenreindex
or use label-based indexing. In general, it's a good idea to avoid list comprehensions or other explicit loops with NumPy / Pandas objects.You can use to way below. It's very simple, but similar to the good answer given by Charlie Haley.
Now you have your dataframe with the columns 'b' and 'x' in the end. You can see this video from OSPY : https://youtu.be/RlbO27N3Xg4