python - 如何从一列中对 Pandas 数据框进行排序

我有一个这样的数据框:

print(df)

        0          1     2
0   354.7      April   4.0
1    55.4     August   8.0
2   176.5   December  12.0
3    95.5   February   2.0
4    85.6    January   1.0
5     152       July   7.0
6   238.7       June   6.0
7   104.8      March   3.0
8   283.5        May   5.0
9   278.8   November  11.0
10  249.6    October  10.0
11  212.7  September   9.0

如您所见,月份不是按日历顺序排列的。所以我创建了第二列来获取每个月(1-12)对应的月份数。从那里,我如何根据日历月的顺序对这个数据框进行排序?

最佳答案

使用 sort_values按特定列的值对 df 进行排序:

In [18]:
df.sort_values('2')

Out[18]:
        0          1     2
4    85.6    January   1.0
3    95.5   February   2.0
7   104.8      March   3.0
0   354.7      April   4.0
8   283.5        May   5.0
6   238.7       June   6.0
5   152.0       July   7.0
1    55.4     August   8.0
11  212.7  September   9.0
10  249.6    October  10.0
9   278.8   November  11.0
2   176.5   December  12.0

如果要按两列排序,请将列标签列表传递给 sort_values,列标签根据排序优先级排序。如果您使用 df.sort_values(['2', '0']),结果将按列 2 然后列 0 排序.诚然,这对于本示例来说实际上没有意义,因为 df['2'] 中的每个值都是唯一的。

https://stackoverflow.com/questions/37787698/

相关文章:

linux - cd进入目录没有权限

python - "hashable"在 Python 中是什么意思?

python - 如何将 SqlAlchemy 结果序列化为 JSON?

linux - 什么 linux shell 命令返回字符串的一部分?

python - pip 安装 : Please check the permissions and

linux - Linux Bash 中的双与号 (&&) 和分号 (;) 有什么区别?

python - numpy 矩阵向量乘法

python - 在python中跳过for循环的第一个条目?

python - glob.glob() 的返回值是如何排序的?

linux - 如何获取 Linux/UNIX 上当前的网络接口(interface)吞吐量统计信息