Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 311
j doe Avatar asked Dec 22 '22 21:12

j doe


2 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
like image 94
Quang Hoang Avatar answered May 14 '23 19:05

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
like image 30
Chris Avatar answered May 14 '23 19:05

Chris