Best way to move a column in pandas dataframe to last column in large dataframe

Question:

I have a pandas dataframe with more than 100 columns.
For example in the following df:

df['A','B','C','D','E','date','G','H','F','I']

How can I move date to be the last column? assuming the dataframe is large and i cant write all the column names manually.

Asked By: j doe

||

Answers:

You can try this:

new_cols = [col for col in df.columns if col != 'date'] + ['date']
df = df[new_cols]

Test data:

cols = ['A','B','C','D','E','date','G','H','F','I']
df = pd.DataFrame([np.arange(len(cols))],
                  columns=cols)

print(df)
#    A  B  C  D  E  date  G  H  F  I
# 0  0  1  2  3  4     5  6  7  8  9

Output of the code:

   A  B  C  D  E  G  H  F  I  date
0  0  1  2  3  4  6  7  8  9     5
Answered By: Quang Hoang

Use pandas.DataFrame.pop and pandas.concat:

print(df)
   col1  col2  col3
0     1    11   111
1     2    22   222
2     3    33   333

s = df.pop('col1')
new_df = pd.concat([df, s], 1)
print(new_df)

Output:

   col2  col3  col1
0    11   111     1
1    22   222     2
2    33   333     3
Answered By: Chris

This way :

df_new=df.loc[:,df.columns!='date']
df_new['date']=df['date']
Answered By: Humi

Simple reindexing should do the job:

original = df.columns
new_cols = original.delete(original.get_loc('date'))
df.reindex(columns=new_cols)
Answered By: adrianp

You can use reindex and union:

df.reindex(df.columns[df.columns != 'date'].union(['date']), axis=1) 

Let’s only work with the index headers and not the complete dataframe.

Then, use reindex to reorder the columns.

Output using @QuangHoang setup:

   A  B  C  D  E  F  G  H  I  date
0  0  1  2  3  4  8  6  7  9     5
Answered By: Scott Boston

You can use movecolumn package in Python to move columns:

pip install movecolumn

Then you can write your code as:

import movecolumn as mc
mc.MoveToLast(df,'date')

Hope that helps.

P.S : The package can be found here. https://pypi.org/project/movecolumn/

Answered By: Saad Bin Munir
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.