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.
The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe.
To move a column to first column in Pandas dataframe, we first use Pandas pop() function and remove the column from the data frame. Here we remove column “A” from the dataframe and save it in a variable.
Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.
Press and hold the Shift key, and then drag the column to a new location. You will see a faint "I" bar along the entire length of the column and a box indicating where the new column will be moved. That's it! Release the mouse button, then leave the Shift key and find the column moved to a new position.
You can rearrange columns directly by specifying their order:
df = df[['a', 'y', 'b', 'x']]
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.
>>> df[[c for c in df if c not in ['b', 'x']] + ['b', 'x']] a y b x 0 1 -1 2 3 1 2 -2 4 6 2 3 -3 6 9 3 4 -4 8 12
To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:
cols_at_end = ['b', 'x'] df = df[[c for c in df if c not in cols_at_end] + [c for c in cols_at_end if c in df]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With