首页 > 解决方案 > 如何对 DataFrame 中特定列的行进行排序?

问题描述

我有一个有 10 列的大数据框。我想仅针对特定列(两个)对所有行进行排序。例如,如果这是我的数据框

      A  B  C
   0  5  1  8
   1  8  2  2
   2  9  3  3

我希望它只对 A 和 B 进行排序,但对行进行排序,所以答案应该是:

  A  B  C
0 1  5  8
1 2  8  2
2 3  9  3

谢谢你。

标签: pythonpandas

解决方案


调用np.sort该特定的列子切片并使用以下方法将其分配回来loc

# df.loc[:, ['A', 'B']] = np.sort(df.loc[:, ['A', 'B']], axis=1)   
df.loc[:, ['A', 'B']] = np.sort(df.loc[:, ['A', 'B']])                                                                 
df                                                                                                                     

   A  B  C
0  1  5  8
1  2  8  2
2  3  9  3

推荐阅读