[英]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.