Malik Koné
Malik Koné

Reputation: 675

How to sort Pandas df columns' values based on its position not labels?

There must be an obvious answer but I could neither find it in the sort_values()'s docs nor in related questions posts*

by in df.sort_values() accept columns labels, but How do I sort using the columns' position ?

I came up with this cumbersome code

df.iloc[df.iloc[:,1].sort_values().index]

to sort on the second column.

I was thinking that something like df.sort_values(by=1,axis=1) would exist. So what is syntacticly simple and correct way to do that ?


*Related questions: 1, 2, 3, 4, 5, 5, 6

Upvotes: 5

Views: 2597

Answers (1)

jezrael
jezrael

Reputation: 863291

Simpliest is select columns names by position:

df = df.sort_values(df.columns[1])

Upvotes: 4

Related Questions