0

I have a dataframe containing several columns labelled x1, x2, x3, and x4.

Depending on the analysis, I would need to assign one of the four columns to be the first column when ordering the four columns in the dataframe from left-to-right.

For instance, if I want column 'x2' to be the first I assign it to 'sorter'.

sorter = x2 

Now my question: how I sort the dataframes in the column so that the column assigned to 'sorter' is located in the first column?

EDIT: The order of the rest of the columns should remain unchanged.

7
  • isn't this function what you want to use? pandas.pydata.org/pandas-docs/stable/reference/api/… Commented Mar 1, 2021 at 19:35
  • what is the order of the other columns? does it not matter Commented Mar 1, 2021 at 19:37
  • df.sort_values(['x2','x1','x3','x4'])? Commented Mar 1, 2021 at 19:37
  • and you can use that to swap the columns of your dataframe stackoverflow.com/a/25652061/5228292 Commented Mar 1, 2021 at 19:37
  • 1
    if you don't specify the other columns, it won't sort them. I'm not sure if it uses a stable sorting algorithm, so the order in the rest of the columns might be random Commented Mar 1, 2021 at 19:39

1 Answer 1

2

You can change order of columns like:

data = {'X1':  ['11', '12'],
        'X2': ['21', '22'],
        'X3': ['31', '32']
        }

df = pd.DataFrame(data)
df
    X1  X2  X3
0   11  21  31
1   12  22  32

df = df.reindex(['X3','X1','X2'], axis=1)
df

    X3  X1  X2
0   31  11  21
1   32  12  22

Note : You need to provide desired order.

You can create a function to change order by given column:

def sorter(desired, df):
    columns = df.columns.tolist()
    columns.remove(desired)
    columns.insert(0,desired)
    return df.reindex(columns, axis=1)

sorter('X2',df)

    X2  X1  X3
0   21  11  31
1   22  12  32

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Is there a way to assign the column that I want as 'first column' to a variable (like in my post) and have the order of the rest of the columns remain unchanged?
Hope the sorter function helps. It change first column as given and keep rest of them the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.