Mark D
Mark D

Reputation: 167

Sort_values based on column index

I have seen lots of advice about sorting based on a pandas column name but I am trying to sort based on the column index.

I have included some code to demonstrate what I am trying to do.

import pandas as pd

df = pd.DataFrame({
 'col1' : ['A', 'A', 'B', 'D', 'C', 'D'],
 'col2' : [2, 1, 9, 8, 7, 4],
 'col3': [0, 1, 9, 4, 2, 3],
 })

df2 = df.sort_values(by=['col2'])

I want to sort a number of dataframes that all have different names for the second column. It is not practical to sort based on (by=['col2'] but I always want to sort on the second column (i.e. Column index 1). Is this possible?

Upvotes: 5

Views: 12672

Answers (1)

jezrael
jezrael

Reputation: 862671

Select columns name by position and pass to by parameter:

print (df.columns[1])
col2

df2 = df.sort_values(by=df.columns[1])
print (df2)
  col1  col2  col3
1    A     1     1
0    A     2     0
5    D     4     3
4    C     7     2
3    D     8     4
2    B     9     9

Upvotes: 11

Related Questions