2015-07-22 73 views
2

我在使用R幾年後學習熊貓。我想根據列中的最大值安排數據框中列的順序。下面的R代碼示例代碼中熊貓的等效代碼是什麼?熊貓的等價物R的順序()用於排列數據幀列

# R code 
test = data.frame(matrix(1:9,ncol = 3)) 
test[,order(apply(test, 2, max),decreasing = TRUE)] 

下面是我在熊貓不成功地試圖:

# Python code 
test = pd.DataFrame({"c":[1,2,3], 
        "a":[4,5,6], 
        "t":[7,8,9]}) 
test = test.sort_index(axis=1, ascending=False) 

顯然,這只是他們安排根據名稱列。我用c,a,t來檢查這種行爲。我怎樣才能複製我在R中做的事情?

回答

3

我敢肯定有一個更簡潔的版本,但這裏有一個選項:

test[test.max(columns=1).order(ascending=False).index] 
  • test.max(columns=1)發現在每列最大(如R的apply(test, 2, max)
  • .order(ascending=False).index是如R的order(,,, decreasing=T)
  • test[ column_numbers ]重新排列列。