python - 在 DataFrame Pandas 中对数据进行排序

标签 python pandas

我获得了以下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

我想对 System_num 中每个数字的 Dis 列中的值进行排序(升序),我的意思是:

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

最佳答案

使用 sort_valuesSystem_num 作为排序依据的第一列

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

enter image description here

另一种不对 System_num 列进行排序的方法

设置

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

关于python - 在 DataFrame Pandas 中对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903174/

相关文章:

python - 我怎样才能填表? ( python , Django )

python - 在 python 中使用 ElementTree 将 xml 元素作为第一个子元素插入

python - pandas 列中字符串值的累积集合

python - 如何根据其他两个系列及其索引创建 Pandas 系列?

python - 在 python pandas 数据框中使用精确颜色重叠透明区域的自定义图例 stacked=false?

python - Python 中的每个文件都被视为一个模块吗?

Python Mypy 属性错误

python - Pandas 创建只有列名的空 DataFrame

python - 将数据帧/系列拆分为每个可能的 block

python - Pandas sklearn one-hot 编码数据帧还是 numpy?