Pandas Series.nunique() 函数
Jinku Hu
2023年1月30日
2020年6月17日
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
当 dropna
为 False
时,Series.nunique()
方法也计入 NaN
。
Author: Jinku Hu
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