cbrnr cbrnr - 16 days ago 9
Python Question

Sort values in a Pandas data frame by a temporary variable

In R, I can use

dplyr::arrange
to sort a data frame by a temporary variable. For example, using the NYC
flights
dataset in the
nycflights13
package, I can sort by velocity by computing this value from the
distance
and
air_time
columns:

library(nycflights13)
arrange(flights, distance / air_time)


Is it possible to achieve this with Pandas (without explicitly creating a new column, sorting by that column, and then removing this column again)?

Answer

I think it is possible by reindex, first can use Series.sort_values for sorting:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

print (df.A / df.D)
0    1.000000
1    0.666667
2    0.600000
dtype: float64

print ((df.A / df.D).sort_values())
2    0.600000
1    0.666667
0    1.000000
dtype: float64

print (df.reindex((df.A / df.D).sort_values().index))
   A  B  C  D  E  F
2  3  6  9  5  6  3
1  2  5  8  3  3  4
0  1  4  7  1  5  7
Comments