如何按一列的值对 pandas dataframe 进行排序
我们将介绍 pandas.dataframe.sort_values
方法来对 dataframe
值进行排序,以及类似 ascending
选项来指定排序顺序,以及 na_position
来确定 nan 在排序结果中的位置。
参考下面的 dataframe
,
import pandas as pd
df = pd.dataframe(
{
"col1": ["g", "t", "n", "w", "n", "g"],
"col2": [5, 2, 5, 1, 3, 6],
"col3": [0, 7, 2, 8, 1, 2],
}
)
print(df)
如果运行此代码,你将得到以下尚未排序的输出。
col1 col2 col3
0 g 5 0
1 t 2 7
2 n 5 2
3 w 1 8
4 n 3 1
5 g 6 2
现在我们可以使用以下代码对 dataframe
进行排序。
import pandas as pd
df = pd.dataframe(
{
"col1": ["g", "t", "n", "w", "n", "g"],
"col2": [5, 2, 5, 1, 3, 6],
"col3": [0, 7, 2, 8, 1, 2],
}
)
print(df.sort_values(by=["col1"]))
我们按 col1
对 dataframe
进行了排序。运行上面的代码后,你将获得以下输出。
col1 col2 col3
0 g 5 0
5 g 6 2
2 n 5 2
4 n 3 1
1 t 2 7
3 w 1 8
我们也可以使用多个列进行排序,让我们如下更改上述代码的最后一行,
print(df.sort_values(by=["col1", "col2"]))
运行代码后,我们将获得以下输出。
col1 col2 col3
0 g 5 0
5 g 6 2
4 n 3 1
2 n 5 2
1 t 2 7
3 w 1 8
现在,dataframe
也通过 col2
进一步排序。
dataframe
排序顺序-参数 ascending
默认情况下,排序按升序排列,要按降序更改 dataframe
,我们需要设置标志 ascending=false
。
print(df.sort_values(by=["col1", "col2"], ascending=false))
运行代码后,我们将获得以下输出。
col1 col2 col3
3 w 1 8
1 t 2 7
2 n 5 2
4 n 3 1
5 g 6 2
0 g 5 0
dataframe
排序顺序 - 参数 na_position
na_position
在排序后指定 nan
的位置.last
将 nan
放在排序的最后,它的默认值是 first
,将 nan
放在排序结果的开头。
参考下面的 dataframe
,
import numpy as np
import pandas as pd
s = pd.series([np.nan, 2, 4, 10, 7])
print(s.sort_values(na_position="last"))
运行代码后,我们将获得以下输出。
1 2.0
2 4.0
4 7.0
3 10.0
0 nan
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串