首页 > 解决方案 > 基于列索引的 sort_values

问题描述

我已经看到很多关于基于 pandas 列名进行排序的建议,但我正在尝试根据列索引进行排序。

我已经包含了一些代码来演示我正在尝试做的事情。

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'])

我想对第二列具有不同名称的许多数据框进行排序。基于 (by=['col2'] 排序是不切实际的,但我总是想在第二列(即列索引 1)上排序。这可能吗?

标签: pythonpython-3.xpandassorting

解决方案


按位置选择列名称并传递给by参数:

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

推荐阅读