Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a pandas series of both index and values? [duplicate]

I have a Series that looks like:

146tf150p    1.000000
havent       1.000000
home         1.000000
okie         1.000000
thanx        1.000000
er           1.000000
anything     1.000000
lei          1.000000
nite         1.000000
yup          1.000000
thank        1.000000
ok           1.000000
where        1.000000
beerage      1.000000
anytime      1.000000
too          1.000000
done         1.000000
645          1.000000
tick         0.980166
blank        0.932702
dtype: float64

I would like to order it by value, but also by index. So I would have smallest numbers at top but respecting the alphabetical order of the indexes.

like image 381
pceccon Avatar asked Aug 11 '17 22:08

pceccon


People also ask

Can a pandas index have duplicates?

duplicated() function Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated.

Can you sort a series in pandas?

pandas Series. sort_values() function is used to sort values on Series object. It sorts the series in ascending order or descending order, by default it does in ascending order. You can specify your preference using the ascending parameter which is True by default.

Which method should I apply to a series or DataFrame to sort the entries by index?

To sort by index / columns (row/column names), use the sort_index() method.


1 Answers

Use np.lexsort to get the ordered positions and pass to iloc

ser.iloc[np.lexsort([ser.index, ser.values])]

blank        0.932702
tick         0.980166
146tf150p    1.000000
645          1.000000
anything     1.000000
anytime      1.000000
beerage      1.000000
done         1.000000
er           1.000000
havent       1.000000
home         1.000000
lei          1.000000
nite         1.000000
ok           1.000000
okie         1.000000
thank        1.000000
thanx        1.000000
too          1.000000
where        1.000000
yup          1.000000
dtype: float64
like image 69
piRSquared Avatar answered Sep 27 '22 17:09

piRSquared