Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data in DataFrame Pandas

Tags:

python

pandas

I obtained the following DataFrame:

    Dis        System_num  Energy
0   0.9           1       -2.3108
1   0.7           1       11.8735
2   1.2           1       -2.3408
3   2.0           1       -0.3485
4   2.0           2       -0.9379
5   0.7           2       7.4776
6   1.5           2       -2.2877
7   0.9           2       -4.1789
8   2.0           3       -3.6596
9   1.0           3       -18.4582
10  0.9           3       -16.2202
11  0.7           3       16.6290

I want to sort values (ascending) in the Dis column for each number in System_num, I mean:

0   0.7           1       11.8735
1   0.9           1       -2.3108
2   1.2           1       -2.3408
3   2.0           1       -0.3485
4   0.7           2       7.4776
5   0.9           2       -4.1789
6   1.5           2       -2.2877
7   2.0           2       -0.9379
8   0.7           3       16.6290
8   0.9           3       -16.2202
10  1.0           3       -18.4582
11  2.0           3       -3.6596
like image 969
Monica Avatar asked Apr 11 '26 19:04

Monica


1 Answers

use sort_values with System_num as the first column to sort by

df.sort_values(['System_num', 'Dis'])

enter image description here

Another way to do it without sorting the System_num column

setup

df = pd.DataFrame([
        [  2.    ,   2.    ,  -0.9379],
        [  0.7   ,   2.    ,   7.4776],
        [  1.5   ,   2.    ,  -2.2877],
        [  0.9   ,   2.    ,  -4.1789],
        [  0.9   ,   1.    ,  -2.3108],
        [  0.7   ,   1.    ,  11.8735],
        [  1.2   ,   1.    ,  -2.3408],
        [  2.    ,   1.    ,  -0.3485],
        [  2.    ,   3.    ,  -3.6596],
        [  1.    ,   3.    , -18.4582],
        [  0.9   ,   3.    , -16.2202],
        [  0.7   ,   3.    ,  16.629 ]
    ], columns=['Dis', 'System_num', 'Energy'])

df.groupby('System_num', sort=False) \
    .apply(pd.DataFrame.sort_values, by='Dis') \
    .reset_index(drop=True)

enter image description here

like image 161
piRSquared Avatar answered Apr 14 '26 08:04

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!