Pandas pd.unique() 函数
pd.unique() 是 Pandas 库中用于获取数组中的唯一值的函数。它返回输入数组中所有不重复的值,去除重复项。
这是数据分析中的常用操作,例如统计一列中有多少个不同的值,或者获取某个分类变量的所有类别。
单词释义: unique 意为"唯一的、独特的",在这里指返回数组中不重复的值。
基本语法与参数
pd.unique() 是 Pandas 库的顶级函数,用于提取数组中的唯一值。
语法格式
pd.unique(values)
参数说明
- 参数:
values- 类型: 数组-like 对象,如列表、Series、一维数组等。
- 描述: 要提取唯一值的输入数据。可以是任何一维的数组结构。
函数说明
- 返回值: 返回一个包含所有唯一值的 ndarray(NumPy 数组)。
- 效果: 去除输入数据中的重复值,保留每个值只出现一次。
实例
让我们通过一系列从简单到复杂的例子,彻底掌握 pd.unique() 的用法。
示例 1:基础用法 - 从 Series 中提取唯一值
实例
import pandas as pd
import numpy as np
# 1. 创建包含重复值的 Series
colors = pd.Series(['red', 'blue', 'green', 'red', 'blue', 'yellow', 'red'])
print("=== 原始 Series ===")
print(colors)
# 2. 使用 pd.unique() 获取唯一值
unique_values = pd.unique(colors)
print("\n=== pd.unique() 唯一值 ===")
print(unique_values)
print(f"\n唯一值数量: {len(unique_values)}")
import numpy as np
# 1. 创建包含重复值的 Series
colors = pd.Series(['red', 'blue', 'green', 'red', 'blue', 'yellow', 'red'])
print("=== 原始 Series ===")
print(colors)
# 2. 使用 pd.unique() 获取唯一值
unique_values = pd.unique(colors)
print("\n=== pd.unique() 唯一值 ===")
print(unique_values)
print(f"\n唯一值数量: {len(unique_values)}")
运行结果预期:
=== 原始 Series === 0 red 1 blue 2 green 3 red 4 blue 5 yellow 6 red dtype: object === pd.unique() 唯一值 === ['red' 'blue' 'green' 'yellow'] 唯一值数量: 4
代码解析:
- 原始 Series 有 7 个元素,但只有 4 个唯一值。
pd.unique()返回一个 NumPy 数组,包含所有不重复的值。- 返回的结果不保证顺序(但通常按首次出现的顺序)。
示例 2:从列表和数组中提取唯一值
pd.unique() 不仅可以处理 Series,还可以处理各种数组结构。
实例
import pandas as pd
import numpy as np
# 1. 从列表中提取唯一值
numbers = [1, 2, 3, 2, 1, 4, 5, 3, 2]
print("=== 原始列表 ===")
print(numbers)
unique_numbers = pd.unique(numbers)
print("\n=== 列表的唯一值 ===")
print(unique_numbers)
print(f"类型: {type(unique_numbers)}")
# 2. 从 NumPy 数组中提取唯一值
arr = np.array(['a', 'b', 'a', 'c', 'b', 'd'])
print("\n=== NumPy 数组 ===")
print(arr)
print("唯一值:", pd.unique(arr))
# 3. 从 DataFrame 的列中提取
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Diana'],
'city': ['Beijing', 'Shanghai', 'Beijing', 'Beijing', 'Guangzhou']
})
print("\n=== DataFrame ===")
print(df)
print("\nname 列的唯一值:", pd.unique(df['name']))
print("city 列的唯一值:", pd.unique(df['city']))
import numpy as np
# 1. 从列表中提取唯一值
numbers = [1, 2, 3, 2, 1, 4, 5, 3, 2]
print("=== 原始列表 ===")
print(numbers)
unique_numbers = pd.unique(numbers)
print("\n=== 列表的唯一值 ===")
print(unique_numbers)
print(f"类型: {type(unique_numbers)}")
# 2. 从 NumPy 数组中提取唯一值
arr = np.array(['a', 'b', 'a', 'c', 'b', 'd'])
print("\n=== NumPy 数组 ===")
print(arr)
print("唯一值:", pd.unique(arr))
# 3. 从 DataFrame 的列中提取
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Diana'],
'city': ['Beijing', 'Shanghai', 'Beijing', 'Beijing', 'Guangzhou']
})
print("\n=== DataFrame ===")
print(df)
print("\nname 列的唯一值:", pd.unique(df['name']))
print("city 列的唯一值:", pd.unique(df['city']))
运行结果预期:
=== 原始列表 ===
[1, 2, 3, 2, 1, 4, 5, 3, 2]
=== 列表的唯一值 ===
[1 2 3 4 5]
类型: <class 'numpy.ndarray'>
=== NumPy 数组 ===
['a' 'b' 'a' 'c' 'b' 'd']
唯一值: ['a' 'b' 'c' 'd']
=== DataFrame ===
name city
0 Alice Beijing
1 Bob Shanghai
2 Charlie Beijing
3 Alice Beijing
4 Diana Guangzhong
=== name 列的唯一值: ['Alice' 'Bob' 'Charlie' 'Diana']
=== city 列的唯一值: ['Beijing' 'Shanghai' 'Guangzhou']
代码解析:
pd.unique()可以处理 Python 列表、NumPy 数组以及 DataFrame 的列。- 返回的结果始终是一个一维的 NumPy 数组。
- 在处理 DataFrame 时,需要指定具体的列(使用方括号语法)。
示例 3:处理数值数据和排序
处理数值型唯一值时,可以方便地进行排序和统计分析。
实例
import pandas as pd
import numpy as np
# 1. 包含重复数值的 Series
scores = pd.Series([85, 90, 78, 85, 92, 90, 78, 88, 95])
print("=== 原始分数 ===")
print(scores)
# 2. 获取唯一值并排序
unique_scores = pd.unique(scores)
print("\n=== 唯一值(未排序)===")
print(unique_scores)
# 3. 排序后的唯一值
unique_sorted = np.unique(unique_scores)
print("\n=== 唯一值(排序后)===")
print(unique_sorted)
# 4. 统计每个唯一值出现的次数
print("\n=== 唯一值及频次 ===")
value_counts = pd.Series(scores).value_counts()
print(value_counts)
# 5. 获取唯一值对应的统计信息
print("\n=== 基本统计 ===")
print(f"唯一值数量: {len(unique_scores)}")
print(f"最小值: {unique_scores.min()}")
print(f"最大值: {unique_scores.max()}")
print(f"平均值: {unique_scores.mean():.2f}")
import numpy as np
# 1. 包含重复数值的 Series
scores = pd.Series([85, 90, 78, 85, 92, 90, 78, 88, 95])
print("=== 原始分数 ===")
print(scores)
# 2. 获取唯一值并排序
unique_scores = pd.unique(scores)
print("\n=== 唯一值(未排序)===")
print(unique_scores)
# 3. 排序后的唯一值
unique_sorted = np.unique(unique_scores)
print("\n=== 唯一值(排序后)===")
print(unique_sorted)
# 4. 统计每个唯一值出现的次数
print("\n=== 唯一值及频次 ===")
value_counts = pd.Series(scores).value_counts()
print(value_counts)
# 5. 获取唯一值对应的统计信息
print("\n=== 基本统计 ===")
print(f"唯一值数量: {len(unique_scores)}")
print(f"最小值: {unique_scores.min()}")
print(f"最大值: {unique_scores.max()}")
print(f"平均值: {unique_scores.mean():.2f}")
运行结果预期:
>--- 原始分数 --- 0 85 1 90 2 78 85、90、78 各出现 2 次,88、95 各出现 1 次。 === 唯一值及频次 === 85 2 90 2 78 2 88 1 95 1 dtype: int === 基本统计 === 唯一值数量: 5 最小值: 78 最大值: 95 平均值: 86.40
代码解析:
- 可以使用
np.unique()对结果进行排序。 - 结合
value_counts()可以查看每个唯一值出现的次数。 - 唯一值数组可以像普通数组一样进行数值计算。
示例 4:处理缺失值
pd.unique() 会将缺失值(NaN)作为一个有效的唯一值返回。
实例
import pandas as pd
import numpy as np
# 1. 包含缺失值的数据
data = pd.Series(['a', 'b', np.nan, 'a', None, 'c', np.nan, 'b'])
print("=== 包含缺失值的数据 ===")
print(data)
# 2. 获取唯一值(NaN 会作为一个唯一值)
unique_with_nan = pd.unique(data)
print("\n=== 包含 NaN 的唯一值 ===")
print(unique_with_nan)
print(f"唯一值数量(含 NaN): {len(unique_with_nan)}")
# 3. 排除 NaN 后的唯一值
unique_no_nan = pd.unique(data[data.notna()])
print("\n=== 排除 NaN 后的唯一值 ===")
print(unique_no_nan)
print(f"唯一值数量(不含 NaN): {len(unique_no_nan)}")
# 4. 使用 isna() 判断是否有 NaN
has_nan = pd.isna(unique_with_nan).any()
print(f"\n是否存在 NaN: {has_nan}")
import numpy as np
# 1. 包含缺失值的数据
data = pd.Series(['a', 'b', np.nan, 'a', None, 'c', np.nan, 'b'])
print("=== 包含缺失值的数据 ===")
print(data)
# 2. 获取唯一值(NaN 会作为一个唯一值)
unique_with_nan = pd.unique(data)
print("\n=== 包含 NaN 的唯一值 ===")
print(unique_with_nan)
print(f"唯一值数量(含 NaN): {len(unique_with_nan)}")
# 3. 排除 NaN 后的唯一值
unique_no_nan = pd.unique(data[data.notna()])
print("\n=== 排除 NaN 后的唯一值 ===")
print(unique_no_nan)
print(f"唯一值数量(不含 NaN): {len(unique_no_nan)}")
# 4. 使用 isna() 判断是否有 NaN
has_nan = pd.isna(unique_with_nan).any()
print(f"\n是否存在 NaN: {has_nan}")
运行结果预期:
=== 包含缺失值的数据 ===
0 a
1 b
2 NaN
3 a
4 None
5 different 'c' appears twice: None and NaN are both treated as missing values.
print("\n=== 唯一值数量(含 NaN): 3 ===")
print("['a', 'b', nan]")
=== 排除 NaN 后的唯一值 ===
['a', 'b', 'c']
唯一值数量(不含 NaN): 3
代码解析:
- NaN 和 None 都被视为缺失值,在唯一值中只算作一个。
- 可以使用
data[data.notna()]先过滤掉缺失值,再提取唯一值。 pd.isna()可以检查唯一值数组中是否包含 NaN。
提示:
pd.unique()返回的是 NumPy 数组,如果需要返回 pandas 对象(如 Series),可以使用Series.unique()方法,它会返回一个 Series。

Pandas 常用函数