pandas.core.groupby.DataFrameGroupBy.count#

DataFrameGroupBy.count()[源代码]#

计算组的数量,排除缺失值。

返回:
Series 或 DataFrame

每个组内值的数量。

参见

Series.groupby

对一个Series应用groupby函数。

DataFrame.groupby

对DataFrame的每一行或每一列应用一个groupby函数。

示例

对于 SeriesGroupBy:

>>> lst = ["a", "a", "b"]
>>> ser = pd.Series([1, 2, np.nan], index=lst)
>>> ser
a    1.0
a    2.0
b    NaN
dtype: float64
>>> ser.groupby(level=0).count()
a    2
b    0
dtype: int64

对于 DataFrameGroupBy:

>>> data = [[1, np.nan, 3], [1, np.nan, 6], [7, 8, 9]]
>>> df = pd.DataFrame(
...     data, columns=["a", "b", "c"], index=["cow", "horse", "bull"]
... )
>>> df
        a         b     c
cow     1       NaN     3
horse   1       NaN     6
bull    7       8.0     9
>>> df.groupby("a").count()
    b   c
a
1   0   2
7   1   1

对于重采样器:

>>> ser = pd.Series(
...     [1, 2, 3, 4],
...     index=pd.DatetimeIndex(
...         ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"]
...     ),
... )
>>> ser
2023-01-01    1
2023-01-15    2
2023-02-01    3
2023-02-15    4
dtype: int64
>>> ser.resample("MS").count()
2023-01-01    2
2023-02-01    2
Freq: MS, dtype: int64