Issue
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?
Solution
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]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.