Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫';s相当于R';s order()用于排列数据帧列_Python_R_Pandas - Fatal编程技术网

Python 熊猫';s相当于R';s order()用于排列数据帧列

Python 熊猫';s相当于R';s order()用于排列数据帧列,python,r,pandas,Python,R,Pandas,在使用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

在使用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中所做的工作?

我确信有一个更简洁的版本,但这里有一个选项:

test[test.max(columns=1).order(ascending=False).index]
  • test.max(columns=1)
    查找每列中的最大值(如R的
    apply(test,2,max)
  • .order(升序=False)。索引类似于R的
    顺序(,,降序=T)
  • 测试[列编号]
    重新排列列

答案很好,有一个小的更新:从pandas 0.24.2开始
pandas.Series.order()
。现在使用
pandas.Series.sort\u values().index
,即返回已排序序列的索引,可以实现与R的
order()
相同的效果。