我在 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_itemKeyError: ('col1', 'col2')输入和期望的输出是:
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
通过 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
添加回答
举报
0/150
提交
取消