How to invert the order of columns of a Dataframe with Python

Asked

Viewed 3,465 times

3

Oops, I wonder how I can invert entire columns with using python.

FRUTA   |   VITAMINA   |   PREÇO
LARANJA |      C       |   2.00
MAÇÃ    |      B1      |   2.00
BANANA  |      B2      |   1.00

I would like to know how I can transform the previous column into the current column:

PREÇO   |   VITAMINA   |   FRUTA
2.00    |      C       |   LARANJA
2.00    |      B1      |   MAÇÃ
1.00    |      B2      |   BANANA

I just want to change the whole column with all the values, how can I do that? Thank you =)

2 answers

5

Suppose the column names of your Dataframe (DF) are "fruit", "vitamin" and "price" in that order. You can reorder it as follows:

df = df[['preço', 'vitamina', 'fruta']]

I mean, you need to pass one list filtering or reordering with the column names you need/want.

  • exactly what I wanted! Thank you Leonardo!

0

A very generic way of reversing the order of the columns is selected the columns back to front inside the loc

df.loc[:,::-1]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.