繁体   English   中英

从 20 列的数据框中仅对 2 列进行排序

[英]Sort only 2 Columns from a Dataframe of 20 Columns

我在 5 行的组(数据框)中有 20 列。 我想强制只对 2 列进行排序并保持其他列不变。

我试过使用

group2['Col1','Col2'] = group2['Col1','Col2'].sort_values(by=['Col2']) 

它产生错误

return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: ('col1', 'col2')

输入和期望的输出是:

在此处输入图片说明

通过 double []创建子集并分配回 numpy 数组:

group2 = pd.DataFrame({
         'Col1':list('nyynny'),
         'Col2':[1,3,5,7,2,0],
         'Col3':[4,5,4,5,5,4],
         'Col4':[7,8,9,4,2,3],
         'Col5':[5,3,6,9,2,4],
         'Col6':list('aaabbb')
})
group2[['Col1','Col2']] = group2[['Col1','Col2']].apply(np.sort).values 
print (group2)
  Col1  Col2  Col3  Col4  Col5 Col6
0    n     0     4     7     5    a
1    n     1     5     8     3    a
2    n     2     4     9     6    a
3    y     3     5     4     9    b
4    y     5     5     2     2    b
5    y     7     4     3     4    b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM