# Reverse column order in pandas - Python
Data Science for Political and Social Phenomena
Author: Guillaume Redoulès

# Reverse column order in pandas

    # Import modules
    import pandas as pd

    # Example dataframe

    raw_data  = {'fruit': ['Banana', 'Orange', 'Apple', 'lemon', "lime", "plum"],
            'color': ['yellow', 'orange', 'red', 'yellow', "green", "purple"],
            'kcal': [89, 47, 52, 15, 30, 28]
        }

    df = pd.DataFrame(raw_data, columns = ['fruit', 'color', 'kcal'])
    df

| fruit | color | kcal
--- | --- | --- | ---
0 | Banana | yellow | 89
1 | Orange | orange | 47
2 | Apple | red | 52
3 | lemon | yellow | 15
4 | lime | green | 30
5 | plum | purple | 28

The columns of a dataframe can be reversed by using the loc accessor and passing `:,::-1`. The `:` before the `,` means select all rows and the `::-1` after the `,` means reverse the column order

    df.loc[:,::-1]

| kcal | color | fruit
--- | --- | --- | ---
0 | 89 | yellow | Banana
1 | 47 | orange | Orange
2 | 52 | red | Apple
3 | 15 | yellow | lemon
4 | 30 | green | lime
5 | 28 | purple | plum

### Find an error or bug? Have a suggestion?

Everything on this site is avaliable on GitHub. Head on over and submit an issue. You can also message me directly by email.