Pandas pd.unique() function
pd.unique() is a function in the Pandas library used toGet the unique values in an arrayfunction. It returns all distinct values from the input array, removing duplicates.
This is a common operation in data analysis, such as counting how many distinct values a column has, or getting all categories of a categorical variable.
Word meaning: unique It means "unique" or "distinct", and here it refers to returning the non-duplicate values in an array.
Basic syntax and parameters
pd.unique() is a top-level function in the Pandas library used to extract unique values from an array.
Syntax format
pd.unique(values)
Parameter Description
- Parameters:
values - Type: array-like object, such as a list, Series, or one-dimensional array.
- Description: the input data from which to extract unique values. It can be any one-dimensional array structure.
Function description
- Return Value: Returns an ndarray (NumPy array) containing all unique values.
- effect: Removes duplicate values from the input data, keeping each value only once.
Example
Let us thoroughly master pd.unique() through a series of examples from simple to complex.
Example 1: Basic usage - extracting unique values from a Series
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a Series with duplicate values
colors
=
pd.
Series
(
[
'red'
,
'blue'
,
'green'
,
'red'
,
'blue'
,
'yellow'
,
'red'
]
)
(
"=== Original Series ==="
)
(
colors
)
2. Getting unique values with pd.unique()
unique_values
=
pd.
unique
(
colors
)
(
"\n=== pd.unique() unique values ==="
)
(
unique_values
)
(
f
"\nNumber of unique values: {len(unique_values)}"
)
Expected output:
=== 原始 Series ===
0 red
1 blue
2 green
3 red
4 blue
5 yellow
6 red
dtype: object
=== pd.unique() 唯一值 ===
['red' 'blue' 'green' 'yellow']
唯一值数量: 4
Code analysis:
- The original Series has 7 elements but only 4 unique values.
pd.unique()It returns a NumPy array containing all distinct values.- The returned result does not guarantee order (but is usually in order of first appearance).
Example 2: Extracting unique values from lists and arrays
pd.unique() It can handle not only Series but also various array structures.
Example
import
pandas
as
pd
import
numpy
as
np
1. Extracting unique values from a list
numbers
=
[
1
,
2
,
3
,
2
,
1
,
4
,
5
,
3
,
2
]
(
"=== Original list ==="
)
(
numbers
)
unique_numbers
=
pd.
unique
(
numbers
)
(
"\n=== Unique values of the list ==="
)
(
unique_numbers
)
(
f
"Type: {type(unique_numbers)}"
)
2. Extracting unique values from a NumPy array
arr
=
np.
array
(
[
'a'
,
'b'
,
'a'
,
'c'
,
'b'
,
'd'
]
)
(
"\n=== NumPy array ==="
)
(
arr
)
(
"Unique values:"
,
pd.
unique
(
arr
)
)
3. Extracting from a DataFrame column
df
=
pd.
DataFrame
(
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'Alice'
,
'Diana'
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Beijing'
,
'Guangzhou'
]
}
)
(
"\n=== DataFrame ==="
)
(
df
)
(
"\nUnique values of the name column:"
,
pd.
unique
(
df
[
'name'
]
)
)
(
"Unique values of the city column:"
,
pd.
unique
(
df
[
'city'
]
)
)
Expected output:
=== 原始列表 ===
[1, 2, 3, 2, 1, 4, 5, 3, 2]
=== 列表的唯一值 ===
[1 2 3 4 5]
类型:
=== 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']
Code analysis:
pd.unique()Can handle Python lists, NumPy arrays, and DataFrame columns.- The returned result is always a one-dimensional NumPy array.
- When working with a DataFrame, you need to specify a particular column (using bracket syntax).
Example 3: Working with numeric data and sorting
When working with numeric unique values, you can easily sort them and perform statistical analysis.
Example
import
pandas
as
pd
import
numpy
as
np
1. Series with duplicate numeric values
scores
=
pd.
Series
(
[
85
,
90
,
78
,
85
,
92
,
90
,
78
,
88
,
95
]
)
(
"=== Original scores ==="
)
(
scores
)
2. Get unique values and sort
unique_scores
=
pd.
unique
(
scores
)
(
"\n=== Unique values (unsorted) ==="
)
(
unique_scores
)
3. Sorted unique values
unique_sorted
=
np.
unique
(
unique_scores
)
(
"\n=== Unique values (sorted) ==="
)
(
unique_sorted
)
4. Count how many times each unique value appears
(
"\n=== Unique values and counts ==="
)
value_counts
=
pd.
Series
(
scores
)
.
value_counts
(
)
(
value_counts
)
5. Get statistics for the unique values
(
"\n=== Basic statistics ==="
)
(
f
"Number of unique values: {len(unique_scores)}"
)
(
f
"Minimum: {unique_scores.min()}"
)
(
f
"Maximum: {unique_scores.max()}"
)
(
f
"Mean: {unique_scores.mean():.2f}"
)
Expected output:
>--- 原始分数 ---
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
Code analysis:
- You can use the
np.unique()Sort the result. - combined with
value_counts()You can see how many times each unique value appears. - The array of unique values can be used in numeric computations just like a normal array.
Example 4: Handling missing values
pd.unique() It treats missing values (NaN) as a valid unique value and returns them.
Example
import
pandas
as
pd
import
numpy
as
np
1. Data containing missing values
data
=
pd.
Series
(
[
'a'
,
'b'
,
np.
nan
,
'a'
,
None
,
'c'
,
np.
nan
,
'b'
]
)
(
"=== Data containing missing values ==="
)
(
data
)
2. Get unique values (NaN is treated as a unique value)
unique_with_nan
=
pd.
unique
(
data
)
(
"\n=== Unique values including NaN ==="
)
(
unique_with_nan
)
(
f
"Number of unique values (including NaN): {len(unique_with_nan)}"
)
3. Unique values after excluding NaN
unique_no_nan
=
pd.
unique
(
data
[
data.
notna
(
)
]
)
(
"\n=== Unique values excluding NaN ==="
)
(
unique_no_nan
)
(
f
"Number of unique values (excluding NaN): {len(unique_no_nan)}"
)
4. Use isna() to check whether NaN is present
has_nan
=
pd.
isna
(
unique_with_nan
)
.
any
(
)
(
f
"\nNaN present: {has_nan}"
)
Expected output:
=== 包含缺失值的数据 ===
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
Code analysis:
- Both NaN and None are treated as missing values and count as only one unique value.
- You can use the
data[data.notna()]Filter out missing values first, then extract the unique values. pd.isna()You can check whether the array of unique values contains NaN.
Tip:
pd.unique()It returns a NumPy array; if you need a pandas object (such as a Series) instead, you can useSeries.unique()the method, which returns a Series.
Common Pandas functions