Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move column in pandas dataframe

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.

like image 745
user308827 Avatar asked Feb 10 '16 17:02

user308827


People also ask

How do I move a column in a pandas Dataframe?

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.

How do I move a column to the front in pandas?

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.

How do I rearrange column positions in pandas?

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.

How do you change the position of a column?

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.


1 Answers

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]] 
like image 154
Alexander Avatar answered Sep 25 '22 22:09

Alexander