Python 熊猫';s相当于R';s order()用于排列数据帧列
在使用R几年后,我正在学习熊猫。我想根据列中的最大值来安排数据帧中列的顺序。下面的R示例代码中的等效代码是什么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 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]
查找每列中的最大值(如R的test.max(columns=1)
)apply(test,2,max)
.order(升序=False)。索引类似于R的
顺序(,,降序=T)
重新排列列测试[列编号]
pandas.Series.order()
。现在使用pandas.Series.sort\u values().index
,即返回已排序序列的索引,可以实现与R的order()
相同的效果。