I'm learning pandas after using R for several years. I would like to arrange the order of columns in a data frame based on the max value in the column. What is the equivalent in pandas of the R example code below?
# R code
test = data.frame(matrix(1:9,ncol = 3))
test[,order(apply(test, 2, max),decreasing = TRUE)]
Here's what I've attempted unsuccessfully in pandas:
# 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)
Obviously, that just arranges them columns based on the name. I used c, a, t to check for that behavior. How can I replicate what I did in R?
I'm sure there is a more succinct version, but here's one option:
test[test.max(columns=1).order(ascending=False).index]
test.max(columns=1)
finds the max in each column (like R's apply(test, 2, max)
).order(ascending=False).index
is like R's order(,,, decreasing=T)
test[ column_numbers ]
reorders the columns.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments