how to sort columns alphabetically in pandas code example
Example 1: how to sort columns alphabetically in pandas
df = df.reindex(sorted(df.columns), axis=1)
Example 2: pandas sort dataframe alphabetically by column
dict_ = {
'C':[1,2,3,4],
'B':[2,4,5,8],
'A':[7,5,7,8],
'D':[1,7,8,7]
}
from pandas import DataFrame
df = DataFrame(dict_)
df
C B A D
0 1 2 7 1
1 2 4 5 7
2 3 5 7 8
3 4 8 8 7
col = df.columns
col = list(col)
['C', 'B', 'A', 'D']
col.sort()
df = df[col]
df
A B C D
0 7 2 1 1
1 5 4 2 7
2 7 5 3 8
3 8 8 4 7