Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a dataframe column to last column

I want move the column in a dataframe to last column, I tried using shift. But this doesn't change the position.

import pandas a pd
df = #input dataframe
df['x'] = df['x'].shift(axis=1)
Error:
    raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
ValueError: No axis named 1 for object type Series

Are there other options? Could someone please suggest?

like image 310
Natasha Avatar asked Oct 28 '25 09:10

Natasha


1 Answers

You can pop and insert again:

df['X'] = df.pop('X')

example:

df = pd.DataFrame([list('axbc')], columns=['A', 'X', 'B', 'C'])
print(df)

   A  X  B  C
0  a  x  b  c


df['X'] = df.pop('X')
print(df)

   A  B  C  X
0  a  b  c  x

Another, more generic, option would be to reindex, for this you can remove the columns to move last from the index and add them in the end. The advantage is that you can handle many columns at once and chose to more to different spots:

to_move = ['X']
new = df.columns.difference(to_move).to_list()+to_move
# ['A', 'B', 'C', 'X']

df = df[new]
like image 150
mozway Avatar answered Oct 31 '25 01:10

mozway