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?
CodePudding user response:
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]
CodePudding user response:
You can split the columns into "end_cols" and "other_cols" and pass them back to the selector -
# Borrowing @mozway's df
end_col = ['X']
other_cols = [col for col in df.columns if col not in end_col]
df[other_cols end_col]
Output
A B C X
0 a b c x