1. nunique()
DataFrame.
nunique
(axis = 0,dropna = True )
功能:計算請求軸上的不同觀察結果
參數:
- axis : {0或'index',1或'columns'},默認為0。0或'index'用於行方式,1或'列'用於列方式。
- dropna : bool,默認為True,不要在計數中包含NaN。
返回: Series
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]}) >>> df.nunique() A 3 B 1 dtype: int64
>>> df.nunique(axis=1) 0 1 1 2 2 2 dtype: int64
2. count()
DataFrame.
count
(axis = 0,level = None,numeric_only = False )
功能:計算每列或每行的非NA單元格。
None,NaN,NaT和numpy.inf都被視作NA
參數:
- axis : {0或'index',1或'columns'},默認為0(行),如果為每列生成0或'索引'計數。如果為每行生成1或'列'計數。
- level : int或str,可選,如果軸是MultiIndex(分層),則沿特定級別計數,折疊到DataFrame中。一個STR指定級別名稱。
- numeric_only : boolean,默認為False,僅包含float,int或boolean數據。
返回:Series或DataFrame對於每個列/行,非NA / null條目的數量。如果指定了level,則返回DataFrame。
從字典構造DataFrame
>>> df = pd.DataFrame({"Person": ... ["John", "Myla", "Lewis", "John", "Myla"], ... "Age": [24., np.nan, 21., 33, 26], ... "Single": [False, True, True, True, False]}) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False
注意不計數的NA值
>>> df.count() Person 5 Age 4 Single 5 dtype: int64
每行計數:
>>> df.count(axis='columns') 0 3 1 2 2 3 3 3 4 3 dtype: int64
計算MultiIndex的一個級別:
>>> df.set_index(["Person", "Single"]).count(level="Person") Age Person John 2 Lewis 1 Myla 1
參考文獻: