Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.unique() function

Pandas pd.unique() function

Pandas Universal Functions Common Pandas functions


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

- 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


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'

]

)

print

(

"=== Original Series ==="

)

print

(

colors

)

2. Getting unique values with pd.unique()

unique_values

=

pd.

unique

(

colors

)

print

(

"\n=== pd.unique() unique values ==="

)

print

(

unique_values

)

print

(

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:

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

]

print

(

"=== Original list ==="

)

print

(

numbers

)

unique_numbers

=

pd.

unique

(

numbers

)

print

(

"\n=== Unique values of the list ==="

)

print

(

unique_numbers

)

print

(

f

"Type: {type(unique_numbers)}"

)

2. Extracting unique values from a NumPy array

arr

=

np.

array

(

[

'a'

,

'b'

,

'a'

,

'c'

,

'b'

,

'd'

]

)

print

(

"\n=== NumPy array ==="

)

print

(

arr

)

print

(

"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'

]

}

)

print

(

"\n=== DataFrame ==="

)

print

(

df

)

print

(

"\nUnique values of the name column:"

,

pd.

unique

(

df

[

'name'

]

)

)

print

(

"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:

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

]

)

print

(

"=== Original scores ==="

)

print

(

scores

)

2. Get unique values and sort

unique_scores

=

pd.

unique

(

scores

)

print

(

"\n=== Unique values (unsorted) ==="

)

print

(

unique_scores

)

3. Sorted unique values

unique_sorted

=

np.

unique

(

unique_scores

)

print

(

"\n=== Unique values (sorted) ==="

)

print

(

unique_sorted

)

4. Count how many times each unique value appears

print

(

"\n=== Unique values and counts ==="

)

value_counts

=

pd.

Series

(

scores

)

.

value_counts

(

)

print

(

value_counts

)

5. Get statistics for the unique values

print

(

"\n=== Basic statistics ==="

)

print

(

f

"Number of unique values: {len(unique_scores)}"

)

print

(

f

"Minimum: {unique_scores.min()}"

)

print

(

f

"Maximum: {unique_scores.max()}"

)

print

(

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:

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'

]

)

print

(

"=== Data containing missing values ==="

)

print

(

data

)

2. Get unique values (NaN is treated as a unique value)

unique_with_nan

=

pd.

unique

(

data

)

print

(

"\n=== Unique values including NaN ==="

)

print

(

unique_with_nan

)

print

(

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

(

)

]

)

print

(

"\n=== Unique values excluding NaN ==="

)

print

(

unique_no_nan

)

print

(

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

(

)

print

(

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:


Tip: pd.unique() It returns a NumPy array; if you need a pandas object (such as a Series) instead, you can use Series.unique() the method, which returns a Series.

Pandas Common Functions Common Pandas functions