pandas 系列 argsort 如何处理 nan 值?
在 pandas 系列中,argmax() 方法用于对系列的值进行排序,它将返回一个新的系列对象,其索引将对原始系列值进行排序。如果系列对象包含任何空值或缺失值,则 argsort() 方法将 -1 值作为其索引。
要对系列对象的值进行排序,argsort 方法将快速排序算法作为默认算法,我们可以使用 kind 参数应用任何其他排序算法,如‘mergesort’、‘heapsort’、‘stable’。
argsort 方法返回一个系列,其值由索引的排序顺序替换。而且它不会改变原始系列对象的索引标签。
示例 1
import pandas as pd
# 创建系列
series = pd.Series([None,5,2,None,7])
print(series)
# 应用 argsort()
print("Output argsort:", series.argsort())
解释
在下面的例子中,我们使用带有一些 None 值的 python 列表创建了一个系列。然后我们对该系列数据应用了 argsort() 方法。
输出
0 NaN 1 5.0 2 2.0 3 NaN 4 7.0 dtype: float64 Output argsort: 0 -1 1 1 2 0 3 -1 4 2 dtype: int64
在上面的输出块中,我们可以看到 argsort 方法的结果系列对象,其中我们可以观察到 -1 值,它代表原始系列对象的 None 值索引。
示例 2
import pandas as pd
# 创建日期
date = pd.date_range("2021-07-01", periods=5, freq="M")
# 创建带有日期范围索引的 pandas 系列
s = pd.Series([9, None, 2, 5, 6], index=date)
print(s)
# 应用 argsort
print("Output of argsort:",s.argsort())
解释
我们再举一个例子一个 pandas 系列对象来应用 argsort 方法。最初,我们创建了一个 pandas 系列对象,其中包含一个整数值列表和一个 None 值,然后对该数据应用 argsort 方法。系列的索引是日期范围值。
输出
2021-07-31 9.0 2021-08-31 NaN 2021-09-30 2.0 2021-10-31 5.0 2021-11-30 6.0 Freq: M, dtype: float64 Output of argsort: 2021-07-31 1 2021-08-31 -1 2021-09-30 2 2021-10-31 3 2021-11-30 0 Freq: M, dtype: int64
输出系列对象索引标签 2021-07-31 处的元素来自原始系列的第 1 个索引位置,它是最小的数字。 argsort 方法会跳过 None 值,因此它将 -1 表示为该特定元素的索引。
同样,输出系列对象索引标签 2021-11-30 处的元素来自原始系列的第 0 个索引位置,它是原始系列值中的最大数字。 这样,pandas 系列 argmax() 方法就可以处理 None 值。

