How can I sort a column in python3?

Question:

I am creating a tool to automate some tasks. These tasks generate two DataFrames, but when concatenating them the columns are messed up as follows:

   col2  col4  col3 col1
0    A     2     0    a
1    A     1     1    B
2    B     9     9    c
3  NaN     8     4    D
4    D     7     2    e
5    C     4     3    F

But I need to rearrange them so that they look like this:

   col1  col2  col3 col4
0    a     A     0    2
1    B     A     1    1
2    c     B     9    9
3    D   NaN     4    8
4    e     D     2    7
5    F     C     3    4

Can someone help me?

I tried with sort_values, but it didn’t work, and I can’t find anywhere another way to try to solve the problem.

Answers:

You can do:

df = df[sorted(df.columns.tolist())].copy()
Answered By: SomeDude
df = df[['col1', 'col2', 'col3', 'col4']]
Answered By: supersquires

use following code:

df.sort_index(axis=1)
Answered By: Panda Kim