Pandas Series.nunique() 函式

Jinku Hu 2023年1月30日 2020年6月17日
  1. pandas.Series.nunique() 語法
  2. 示例程式碼:Series.nunique() 方法
  3. 示例程式碼: Series.nunique() 方法的 dropna=False
Pandas Series.nunique() 函式

Python Pandas Series.nunique()方法計算 Python Pandas Series 中的唯一值。

pandas.Series.nunique() 語法

Series.nunique(dropna=True)

引數

dropna 預設為 True
如果為 True,則 NaN 被排除在外;如果為 False,則 NaN 也被計算在內

返回值

它返回一個整數,計算呼叫者 Pandas Series 中的唯一值。

示例程式碼:Series.nunique() 方法

import pandas as pd
import numpy as np

ser = pd.Series([1, 2, 3, np.nan, 3, 4, np.nan],
               name = 'No.')

print(ser.nunique())

輸出:

4

呼叫者 Series 除了 NaN 外有 4 個唯一的值–[1, 2, 3, 4],因此 Series.nunique() 方法返回 4,因為 NaN 被預設排除在外。

示例程式碼: Series.nunique() 方法的 dropna=False

import pandas as pd
import numpy as np

ser = pd.Series([1, 2, 3, np.nan, 3, 4, np.nan],
               name = 'No.')

print(ser.nunique(dropna=False))

輸出:

5

dropnaFalse 時,Series.nunique() 方法也計入 NaN

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Pandas Series