While this question had relative answers, I couldn't find an efficient and robust way of doing it. I have to shift the last column in my data frame to the first without disturbing any of the other columns. How should I do this ? Thanks in advance.


1 Answer 1

cols = list(df.columns)
cols = [cols[-1]] + cols[:-1]
df = df[cols]
  • $\begingroup$ Forgot the list. Edited $\endgroup$
    – Fred
    Sep 24, 2018 at 12:26
  • $\begingroup$ this puts the column in the fifth place and not at the first when I ran this code snippet. $\endgroup$
    – VishwaV
    Sep 24, 2018 at 12:29
  • 1
    $\begingroup$ That's weird. This should work for any regular data frame. I can't help you out without further details then $\endgroup$
    – Fred
    Sep 24, 2018 at 12:50
  • $\begingroup$ Wait, let me post my notebook cloudlink. $\endgroup$
    – VishwaV
    Sep 24, 2018 at 12:53
  • $\begingroup$ Works as expected. $\endgroup$
    – gies0r
    Mar 2, 2020 at 18:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.