Pandas-2-2-中文文档-三十三-
Pandas 2.2 中文文档(三十三)
pandas.core.window.rolling.Rolling.mean
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html
Rolling.mean(numeric_only=False, engine=None, engine_kwargs=None)
计算滚动均值。
参数:
numeric_onlybool,默认为 False
只包括浮点数、整数和布尔值列。
在 1.5.0 版中新增。
enginestr,默认为 None
-
'cython':通过 Cython 的 C 扩展运行操作。 -
'numba':通过 Numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba在 1.3.0 版中新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,该引擎可以接受nopython、nogil和parallel字典键。其值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}在 1.3.0 版中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为 np.float64 数据类型。
另请参见
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrames 调用 rolling。
pandas.Series.mean
对 Series 进行均值聚合。
pandas.DataFrame.mean
对 DataFrame 进行均值聚合。
注意
请参阅 Numba 引擎 和 Numba(JIT 编译) 以获取有关 Numba 引擎的扩展文档和性能考虑。
示例
下面的示例将展示窗口大小分别为两和三时的滚动均值计算。
>>> s = pd.Series([1, 2, 3, 4])
>>> s.rolling(2).mean()
0 NaN
1 1.5
2 2.5
3 3.5
dtype: float64
>>> s.rolling(3).mean()
0 NaN
1 NaN
2 2.0
3 3.0
dtype: float64
pandas.core.window.rolling.Rolling.median
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.median.html
Rolling.median(numeric_only=False, engine=None, engine_kwargs=None)
计算滚动中值。
参数:
numeric_onlybool,默认为 False
仅包含浮点数、整数、布尔值列。
1.5.0 版中新增。
enginestr,默认为 None
-
'cython':通过 C 扩展运行操作。 -
'numba':通过 Numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba1.3.0 版中新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,没有接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}1.3.0 版中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为 np.float64 类型。
参见
使用 Series 数据调用 rolling。
使用 DataFrame 调用 rolling。
系列的中值聚合。
DataFrame 的中值聚合。
注释
查看Numba 引擎和Numba(JIT 编译)以获取关于 Numba 引擎的扩展文档和性能考虑。
示例
计算窗口大小为 3 的系列的滚动中值。
>>> s = pd.Series([0, 1, 2, 3, 4])
>>> s.rolling(3).median()
0 NaN
1 NaN
2 1.0
3 2.0
4 3.0
dtype: float64
pandas.core.window.rolling.Rolling.var
译文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.var.html
Rolling.var(ddof=1, numeric_only=False, engine=None, engine_kwargs=None)
计算滚动方差。
参数:
ddof 整数,默认为 1。
自由度差。计算中使用的除数是 N - ddof,其中 N 表示元素数量。
numeric_only 布尔值,默认为 False。
仅包括浮点数、整数、布尔值列。
新版本 1.5.0 中新增。
engine 字符串,默认为 None。
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba。新版本 1.4.0 中新增。
engine_kwargs 字典,默认为 None。
-
对于
'cython'引擎,没有接受engine_kwargs。 -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}。新版本 1.4.0 中新增。
返回:
Series 或 DataFrame。
返回类型与原始对象相同,具有 np.float64 数据类型。
另请参见
NumPy 数组的等效方法。
pandas.Series.rolling
调用滚动窗口计算 Series 数据。
pandas.DataFrame.rolling
调用滚动窗口计算 DataFrames。
pandas.Series.var
Series 的聚合 var。
pandas.DataFrame.var
DataFrame 的聚合 var。
注意事项
Series.var() 中使用的默认 ddof 为 1,与 numpy.var() 中的默认 ddof 0 不同。
滚动计算需要至少一个周期。
示例
>>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
>>> s.rolling(3).var()
0 NaN
1 NaN
2 0.333333
3 1.000000
4 1.000000
5 1.333333
6 0.000000
dtype: float64
pandas.core.window.rolling.Rolling.std
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.std.html
Rolling.std(ddof=1, numeric_only=False, engine=None, engine_kwargs=None)
计算滚动标准差。
参数:
ddofint,默认为 1
自由度差值。计算中使用的除数是 N - ddof,其中 N 表示元素数目。
numeric_onlybool,默认为 False
仅包括 float、int、boolean 列。
1.5.0 版本中新增。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba1.4.0 版本中新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,没有被接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须为True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}1.4.0 版本中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为 np.float64。
参见
等效于 NumPy 数组的方法。
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrames 调用 rolling。
pandas.Series.std
对 Series 进行聚合的 std。
pandas.DataFrame.std
对 DataFrame 进行聚合的 std。
注意事项
在 Series.std() 中使用的默认 ddof 为 1,与 numpy.std() 中的默认 ddof 0 不同。
滚动计算需要至少一个周期。
示例
>>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
>>> s.rolling(3).std()
0 NaN
1 NaN
2 0.577350
3 1.000000
4 1.000000
5 1.154701
6 0.000000
dtype: float64
pandas.core.window.rolling.Rolling.min
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.min.html
Rolling.min(numeric_only=False, engine=None, engine_kwargs=None)
计算滚动最小值。
参数:
numeric_only 布尔型,默认值为 False
仅包括浮点型、整型和布尔型列。
在版本 1.5.0 中新增。
engine 字符串,默认值为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba在版本 1.3.0 中新增。
engine_kwargs 字典,默认值为 None
-
对于
'cython'引擎,没有接受的engine_kwargs。 -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。 值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}在版本 1.3.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参阅
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrames 调用 rolling。
pandas.Series.min
对 Series 进行最小聚合。
pandas.DataFrame.min
对 DataFrame 进行最小聚合。
注意
参见 Numba 引擎和 Numba(JIT 编译),了解 Numba 引擎的扩展文档和性能考虑。
示例
使用窗口大小为 3 进行滚动最小值计算。
>>> s = pd.Series([4, 3, 5, 2, 6])
>>> s.rolling(3).min()
0 NaN
1 NaN
2 3.0
3 2.0
4 2.0
dtype: float64
pandas.core.window.rolling.Rolling.max
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.max.html
Rolling.max(numeric_only=False, *args, engine=None, engine_kwargs=None, **kwargs)
计算滚动最大值。
参数:
numeric_onlybool,默认值为 False
仅包括 float、int、boolean 列。
新版本 1.5.0 中新增。
enginestr,默认值为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba新版本 1.3.0 中新增。
engine_kwargsdict,默认值为 None
-
对于
'cython'引擎,没有被接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}新版本 1.3.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参见
pandas.Series.rolling
用于 Series 数据的调用滚动。
pandas.DataFrame.rolling
用于 DataFrames 的调用滚动。
pandas.Series.max
Series 的最大值聚合。
pandas.DataFrame.max
DataFrame 的最大值聚合。
注意事项
有关 Numba 引擎的扩展文档和性能考虑,请参阅 Numba engine 和 Numba (JIT compilation)。
示例
>>> ser = pd.Series([1, 2, 3, 4])
>>> ser.rolling(2).max()
0 NaN
1 2.0
2 3.0
3 4.0
dtype: float64
pandas.core.window.rolling.Rolling.corr
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.corr.html
Rolling.corr(other=None, pairwise=None, ddof=1, numeric_only=False)
计算 rolling 相关性。
参数:
otherSeries 或 DataFrame,可选
如果未提供,则默认为self并生成成对输出。
pairwise布尔值,默认为 None
如果为 False,则只会使用self和other之间匹配的列,并且输出将是一个 DataFrame。如果为 True,则将计算所有成对组合,并且在 DataFrame 输入的情况下,输出将是一个 MultiIndexed DataFrame。在存在缺失元素的情况下,只会使用完整的成对观察。
ddof整数,默认为 1
自由度差。计算中使用的除数是N - ddof,其中N表示元素数量。
numeric_only布尔值,默认为 False
仅包括 float、int、boolean 列。
在 1.5.0 版本中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有np.float64数据类型。
另请参阅
cov
用于计算协方差的类似方法。
NumPy Pearson 相关性计算。
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrame 调用 rolling。
pandas.Series.corr
为 Series 聚合corr。
pandas.DataFrame.corr
为 DataFrame 聚合corr。
注意
此函数使用 Pearson 相关性的定义(en.wikipedia.org/wiki/Pearson_correlation_coefficient)。
当未指定other时,输出将是自相关性(例如全部为 1),除了带有pairwise设置为 True 的DataFrame输入。
对于相等值序列的相关性,函数将返回NaN;这是 0/0 除法错误的结果。
当pairwise设置为False时,只会使用self和other之间匹配的列。
当pairwise设置为 True 时,输出将是一个带有原始索引的 MultiIndex DataFrame,第一级为原始索引,第二级为其他 DataFrame 列。
在存在缺失元素的情况下,只会使用完整的成对观察。
示例
下面的示例展示了使用窗口大小为四的 rolling 计算,与使用numpy.corrcoef()等效的函数调用匹配。
>>> v1 = [3, 3, 3, 5, 8]
>>> v2 = [3, 4, 4, 4, 8]
>>> np.corrcoef(v1[:-1], v2[:-1])
array([[1\. , 0.33333333],
[0.33333333, 1\. ]])
>>> np.corrcoef(v1[1:], v2[1:])
array([[1\. , 0.9169493],
[0.9169493, 1\. ]])
>>> s1 = pd.Series(v1)
>>> s2 = pd.Series(v2)
>>> s1.rolling(4).corr(s2)
0 NaN
1 NaN
2 NaN
3 0.333333
4 0.916949
dtype: float64
以下示例展示了在 DataFrame 上使用 pairwise 选项进行类似的滚动计算。
>>> matrix = np.array([[51., 35.],
... [49., 30.],
... [47., 32.],
... [46., 31.],
... [50., 36.]])
>>> np.corrcoef(matrix[:-1, 0], matrix[:-1, 1])
array([[1\. , 0.6263001],
[0.6263001, 1\. ]])
>>> np.corrcoef(matrix[1:, 0], matrix[1:, 1])
array([[1\. , 0.55536811],
[0.55536811, 1\. ]])
>>> df = pd.DataFrame(matrix, columns=['X', 'Y'])
>>> df
X Y
0 51.0 35.0
1 49.0 30.0
2 47.0 32.0
3 46.0 31.0
4 50.0 36.0
>>> df.rolling(4).corr(pairwise=True)
X Y
0 X NaN NaN
Y NaN NaN
1 X NaN NaN
Y NaN NaN
2 X NaN NaN
Y NaN NaN
3 X 1.000000 0.626300
Y 0.626300 1.000000
4 X 1.000000 0.555368
Y 0.555368 1.000000
pandas.core.window.rolling.Rolling.cov
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.cov.html
Rolling.cov(other=None, pairwise=None, ddof=1, numeric_only=False)
计算滚动样本协方差。
参数:
other系列或数据框,可选
如果未提供,则将默认为自身并生成逐对输出。
逐对布尔值,默认为 None
如果为 False,则只使用自身和其他之间匹配的列,并且输出将是一个数据框。如果为 True,则将计算所有两两组合,并且在数据框输入的情况下,输出将是一个多重索引数据框。在缺失元素的情况下,只会使用完整的两两观察。
ddof整数,默认为 1
自由度差分。 计算中使用的除数是 N - ddof,其中 N 表示元素的数量。
numeric_only布尔值,默认为 False
仅包括浮点数、整数和布尔列。
新版本 1.5.0 中的新增内容。
返回:
系列或数据框
返回类型与原始对象相同,数据类型为np.float64。
参见
pandas.Series.rolling
使用系列数据进行滚动调用。
pandas.DataFrame.rolling
使用数据框调用滚动。
pandas.Series.cov
对系列进行聚合的协方差计算。
pandas.DataFrame.cov
对数据框进行聚合的协方差计算。
示例
>>> ser1 = pd.Series([1, 2, 3, 4])
>>> ser2 = pd.Series([1, 4, 5, 8])
>>> ser1.rolling(2).cov(ser2)
0 NaN
1 1.5
2 0.5
3 1.5
dtype: float64
pandas.core.window.rolling.Rolling.skew
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.skew.html
Rolling.skew(numeric_only=False)
计算滚动无偏偏度。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
版本 1.5.0 中的新功能。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参阅
概率密度的第三阶矩。
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrame 调用 rolling。
pandas.Series.skew
为 Series 聚合偏度。
pandas.DataFrame.skew
为 DataFrame 聚合偏度。
注意事项
滚动计算需要至少三个周期。
示例
>>> ser = pd.Series([1, 5, 2, 7, 15, 6])
>>> ser.rolling(3).skew().round(6)
0 NaN
1 NaN
2 1.293343
3 -0.585583
4 0.670284
5 1.652317
dtype: float64
pandas.core.window.rolling.Rolling.kurt
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.kurt.html
Rolling.kurt(numeric_only=False)
计算无偏的滚动峰度的费舍尔定义。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数和布尔值列。
新版本 1.5.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参阅
参考 SciPy 方法。
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrame 调用 rolling。
pandas.Series.kurt
聚合 Series 的峰度。
pandas.DataFrame.kurt
聚合 DataFrame 的峰度。
注意
计算需要至少四个周期。
示例
下面的示例将展示一个滚动计算,窗口大小为四,与使用 scipy.stats 的等效函数调用匹配。
>>> arr = [1, 2, 3, 4, 999]
>>> import scipy.stats
>>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}")
-1.200000
>>> print(f"{scipy.stats.kurtosis(arr[1:], bias=False):.6f}")
3.999946
>>> s = pd.Series(arr)
>>> s.rolling(4).kurt()
0 NaN
1 NaN
2 NaN
3 -1.200000
4 3.999946
dtype: float64
pandas.core.window.rolling.Rolling.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.apply.html
Rolling.apply(func, raw=False, engine=None, engine_kwargs=None, args=None, kwargs=None)
计算滚动自定义聚合函数。
参数:
func函数
如果raw=True,则必须从 ndarray 输入中产生单个值,如果raw=False,则必须从 Series 中产生单个值。还可以接受具有指定engine='numba'的 Numba JIT 函数。
rawbool,默认为 False
-
False:将每行或列作为 Series 传递给函数。 -
True:传递的函数将接收 ndarray 对象。如果只是应用 NumPy 缩减函数,这将实现更好的性能。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行滚动应用。 -
'numba':通过 numba 的 JIT 编译代码运行滚动应用。仅在raw设置为True时可用。 -
None:默认为'cython'或全局设置compute.use_numba
engine_kwargs字典,默认为 None
-
对于'cython'引擎,没有被接受的
engine_kwargs -
对于'numba'引擎,引擎可以接受
nopython,nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False},将应用于func和apply滚动聚合。
args元组,默认为 None
要传递给 func 的位置参数。
kwargs字典,默认为 None
要传递给 func 的关键字参数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有np.float64 dtype。
另请参见
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrames 调用 rolling。
pandas.Series.apply
Series 的聚合应用。
pandas.DataFrame.apply
DataFrame 的聚合应用。
示例
>>> ser = pd.Series([1, 6, 5, 4])
>>> ser.rolling(2).apply(lambda s: s.sum() - s.min())
0 NaN
1 6.0
2 6.0
3 5.0
dtype: float64
pandas.core.window.rolling.Rolling.aggregate
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.aggregate.html
Rolling.aggregate(func, *args, **kwargs)
使用一个或多个操作在指定轴上进行聚合。
参数:
func函数、str、list 或 dict
用于聚合数据的函数。如果是函数,则必须在传递给 Series/Dataframe 或传递给 Series/Dataframe.apply 时起作用。
接受的组合有:
-
函数
-
字符串函数名称
-
函数和/或函数名称的列表,例如
[np.sum, 'mean'] -
轴标签的字典 -> 函数、函数名称或此类列表。
*args
传递给 func 的位置参数。
**kwargs
传递给 func 的关键字参数。
返回:
标量、Series 或 DataFrame
返回可以是:
-
标量:当使用单个函数调用 Series.agg 时
-
Series:当 DataFrame.agg 使用单个函数调用时
-
DataFrame:当 DataFrame.agg 使用多个函数调用时
另请参阅
pandas.Series.rolling
使用 Series 数据调用的对象。
pandas.DataFrame.rolling
用 DataFrame 数据调用的对象。
注释
聚合操作始终在一个轴上执行,可以是索引(默认)或列轴。这种行为与 numpy 聚合函数(mean、median、prod、sum、std、var)不同,numpy 聚合函数的默认行为是计算扁平化数组的聚合,例如,numpy.mean(arr_2d)与numpy.mean(arr_2d, axis=0)不同。`
agg 是 aggregate 的别名。使用别名。
变异传递对象的函数可能会产生意外行为或错误,并且不受支持。有关更多详细信息,请参阅使用用户定义函数 (UDF) 方法进行变异。
传递的用户定义函数将传递一个 Series 进行评估。
示例
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
>>> df
A B C
0 1 4 7
1 2 5 8
2 3 6 9
>>> df.rolling(2).sum()
A B C
0 NaN NaN NaN
1 3.0 9.0 15.0
2 5.0 11.0 17.0
>>> df.rolling(2).agg({"A": "sum", "B": "min"})
A B
0 NaN NaN
1 3.0 4.0
2 5.0 5.0
pandas.core.window.rolling.Rolling.quantile
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.quantile.html
Rolling.quantile(q, interpolation='linear', numeric_only=False)
计算滚动分位数。
参数:
quantilefloat
要计算的分位数。0 <= quantile <= 1。
自 2.1.0 版本起已弃用:将在将来的版本中更名为 ‘q’。
interpolation
此可选参数指定插值方法,当所需分位数位于两个数据点 i 和 j 之间时使用:
- linear:i + (j - i) * fraction,其中 fraction 是被 i 和 j 包围的索引的小数部分。
- lower:i。
- higher:j。
- nearest:最接近的 i 或 j。
- midpoint:(i + j) / 2。
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
自 1.5.0 版本新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参阅
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrame 调用 rolling。
pandas.Series.quantile
Series 的聚合分位数。
pandas.DataFrame.quantile
DataFrame 的聚合分位数。
示例
>>> s = pd.Series([1, 2, 3, 4])
>>> s.rolling(2).quantile(.4, interpolation='lower')
0 NaN
1 1.0
2 2.0
3 3.0
dtype: float64
>>> s.rolling(2).quantile(.4, interpolation='midpoint')
0 NaN
1 1.5
2 2.5
3 3.5
dtype: float64
pandas.core.window.rolling.Rolling.sem
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.sem.html
Rolling.sem(ddof=1, numeric_only=False)
计算滚动平均的标准误差。
参数:
ddof整数,默认为 1
自由度的增量。计算中使用的除数是N - ddof,其中N表示元素的数量。
numeric_only布尔值,默认为 False
仅包括 float、int、boolean 列。
在版本 1.5.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参阅
pandas.Series.rolling
使用 Series 数据进行滚动。
pandas.DataFrame.rolling
使用 DataFrame 进行滚动。
pandas.Series.sem
聚合 Series 的 sem。
pandas.DataFrame.sem
聚合 DataFrame 的 sem。
注释
计算需要至少一个周期。
示例
>>> s = pd.Series([0, 1, 2, 3])
>>> s.rolling(2, min_periods=1).sem()
0 NaN
1 0.707107
2 0.707107
3 0.707107
dtype: float64
pandas.core.window.rolling.Rolling.rank
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.rank.html
Rolling.rank(method='average', ascending=True, pct=False, numeric_only=False)
计算滚动排名。
1.4.0 版新增。
参数:
method,默认为 ‘average’
如何对具有相同值的记录组进行排名(即平局):
-
average:组的平均排名
-
min:组中最低的排名
-
max:组中最高的排名
ascendingbool,默认为 True
是否按升序排列元素。
pctbool,默认为 False
是否在百分位形式中显示返回的排名。
numeric_onlybool,默认为 False
仅包括 float、int、boolean 列。
1.5.0 版新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为 np.float64 数据类型。
另请参阅
使用 Series 数据调用滚动。
使用 DataFrame 调用滚动。
为 Series 聚合排名。
DataFrame 的聚合排名。
示例
>>> s = pd.Series([1, 4, 2, 3, 5, 3])
>>> s.rolling(3).rank()
0 NaN
1 NaN
2 2.0
3 2.0
4 3.0
5 1.5
dtype: float64
>>> s.rolling(3).rank(method="max")
0 NaN
1 NaN
2 2.0
3 2.0
4 3.0
5 2.0
dtype: float64
>>> s.rolling(3).rank(method="min")
0 NaN
1 NaN
2 2.0
3 2.0
4 3.0
5 1.0
dtype: float64
pandas.core.window.rolling.Window.mean
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Window.mean.html
Window.mean(numeric_only=False, **kwargs)
计算滚动加权窗口均值。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
版本 1.5.0 中新增。
**kwargs
用于配置 SciPy 加权窗口类型的关键字参数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参见
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrames 调用 rolling。
pandas.Series.mean
Series 的均值聚合。
pandas.DataFrame.mean
DataFrame 的均值聚合。
示例
>>> ser = pd.Series([0, 1, 5, 2, 8])
要获得 Window 的实例,我们需要传递参数 win_type。
>>> type(ser.rolling(2, win_type='gaussian'))
<class 'pandas.core.window.rolling.Window'>
为了使用 SciPy 的高斯窗口,我们需要提供参数 M 和 std。在我们的示例中,参数 M 对应于 2。我们将第二个参数 std 作为以下方法的参数传递:
>>> ser.rolling(2, win_type='gaussian').mean(std=3)
0 NaN
1 0.5
2 3.0
3 3.5
4 5.0
dtype: float64
pandas.core.window.rolling.Window.sum
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Window.sum.html
Window.sum(numeric_only=False, **kwargs)
计算滚动加权窗口求和。
参数:
numeric_only布尔型,默认为 False
只包括 float、int、boolean 列。
自 1.5.0 版开始引入。
**kwargs
配置 SciPy 加权窗口类型的关键字参数。
返回值:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参阅
使用 Series 数据调用 rolling。
使用 DataFrame 调用 rolling。
用于 Series 的聚合求和。
用于 DataFrame 的聚合求和。
示例
>>> ser = pd.Series([0, 1, 5, 2, 8])
要获得 Window 的实例,我们需要传递参数 win_type。
>>> type(ser.rolling(2, win_type='gaussian'))
<class 'pandas.core.window.rolling.Window'>
为了使用 SciPy 的高斯窗口,我们需要提供参数 M 和 std。参数 M 在我们的示例中对应为 2。我们将第二个参数 std 作为以下方法(在本例中为 sum)的参数传递:
>>> ser.rolling(2, win_type='gaussian').sum(std=3)
0 NaN
1 0.986207
2 5.917243
3 6.903450
4 9.862071
dtype: float64
pandas.core.window.rolling.Window.var
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Window.var.html
Window.var(ddof=1, numeric_only=False, **kwargs)
计算滚动加权窗口方差。
参数:
numeric_onlybool,默认值为 False
只包括浮点数、整数和布尔值列。
自版本 1.5.0 新增。
**kwargs
用于配置 SciPy 加权窗口类型的关键字参数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为np.float64数据类型。
请参见
使用 Series 数据调用 rolling。
使用 DataFrame 调用 rolling。
为 Series 聚合 var。
为 DataFrame 聚合 var。
示例
>>> ser = pd.Series([0, 1, 5, 2, 8])
要获得 Window 的实例,我们需要传递参数 win_type。
>>> type(ser.rolling(2, win_type='gaussian'))
<class 'pandas.core.window.rolling.Window'>
为了使用 SciPy 的高斯窗口,我们需要提供参数 M 和 std。在我们的示例中,参数 M 对应于 2。我们将第二个参数 std 作为以下方法的参数传递:
>>> ser.rolling(2, win_type='gaussian').var(std=3)
0 NaN
1 0.5
2 8.0
3 4.5
4 18.0
dtype: float64
pandas.core.window.rolling.Window.std
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Window.std.html
Window.std(ddof=1, numeric_only=False, **kwargs)
计算滚动加权窗口标准差。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
新版本中新增的功能为 1.5.0。
**kwargs
用于配置SciPy加权窗口类型的关键字参数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为np.float64数据类型。
另请参见
pandas.Series.rolling
使用 Series 数据调用 rolling。
pandas.DataFrame.rolling
使用 DataFrame 调用 rolling。
pandas.Series.std
为 Series 聚合 std。
pandas.DataFrame.std
为 DataFrame 聚合 std。
示例
>>> ser = pd.Series([0, 1, 5, 2, 8])
要获得Window的实例,我们需要传递参数 win_type。
>>> type(ser.rolling(2, win_type='gaussian'))
<class 'pandas.core.window.rolling.Window'>
为了使用 SciPy 高斯窗口,我们需要提供参数 M 和 std。在我们的例子中,参数 M 对应为 2。我们将第二个参数 std 作为以下方法的参数传递:
>>> ser.rolling(2, win_type='gaussian').std(std=3)
0 NaN
1 0.707107
2 2.828427
3 2.121320
4 4.242641
dtype: float64
pandas.core.window.expanding.Expanding.count
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.count.html
Expanding.count(numeric_only=False)
计算非 NaN 观测的扩展计数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为 np.float64。
另请参阅
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrames 调用 expanding。
pandas.Series.count
对 Series 进行计数聚合。
pandas.DataFrame.count
对 DataFrame 进行计数聚合。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().count()
a 1.0
b 2.0
c 3.0
d 4.0
dtype: float64
pandas.core.window.expanding.Expanding.sum
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.sum.html
Expanding.sum(numeric_only=False, engine=None, engine_kwargs=None)
计算扩展总和。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
新版本 1.5.0 中新增。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba新版本 1.3.0 中新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受任何engine_kwargs -
对于
'numba'引擎,该引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}新版本 1.3.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有 np.float64 数据类型。
另请参阅
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrames 调用 expanding。
pandas.Series.sum
Series 的聚合总和。
pandas.DataFrame.sum
DataFrame 的聚合总和。
注意
有关 Numba 引擎的扩展文档和性能考虑,请参阅 Numba engine 和 Numba (JIT compilation)。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().sum()
a 1.0
b 3.0
c 6.0
d 10.0
dtype: float64
pandas.core.window.expanding.Expanding.mean
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.mean.html
Expanding.mean(numeric_only=False, engine=None, engine_kwargs=None)
计算扩展均值。
参数:
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
版本 1.5.0 中的新功能。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 Numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba版本 1.3.0 中的新功能。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,没有接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}版本 1.3.0 中的新功能。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为np.float64。
另请参见
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrame 调用 expanding。
pandas.Series.mean
Series 的均值聚合。
pandas.DataFrame.mean
DataFrame 的均值聚合。
注意事项
有关 Numba 引擎的扩展文档和性能考虑,请参见 Numba engine 和 Numba (JIT compilation)。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().mean()
a 1.0
b 1.5
c 2.0
d 2.5
dtype: float64
pandas.core.window.expanding.Expanding.median
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.median.html
Expanding.median(numeric_only=False, engine=None, engine_kwargs=None)
计算扩展中位数。
参数:
numeric_onlybool,默认值为 False
仅包括浮点型、整型和布尔型列。
新版本 1.5.0 中新增。
enginestr,默认值为 None
-
'cython':通过 cython 的 C 扩展运行操作。
-
'numba':通过 Numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba新版本 1.3.0 中新增。
engine_kwargsdict,默认值为 None
-
对于'cython'引擎,不接受任何'engine_kwargs'
-
对于'numba'引擎,引擎可以接受'nopython'、'nogil'和'parallel'字典键。其值必须为 True 或 False。'numba'引擎的默认'engine_kwargs'是
新版本 1.3.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参见
pandas.Series.expanding
使用 Series 数据调用扩展。
pandas.DataFrame.expanding
使用 DataFrames 调用扩展。
pandas.Series.median
Series 的聚合中位数。
pandas.DataFrame.median
DataFrame 的聚合中位数。
注意事项
参见 Numba 引擎和 Numba(即时编译)以获取 Numba 引擎的扩展文档和性能考虑。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().median()
a 1.0
b 1.5
c 2.0
d 2.5
dtype: float64
pandas.core.window.expanding.Expanding.var
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.var.html
Expanding.var(ddof=1, numeric_only=False, engine=None, engine_kwargs=None)
计算扩展方差。
参数:
ddofint,默认为 1
自由度差。计算中使用的除数是N - ddof,其中N代表元素的数量。
numeric_onlybool,默认为 False
仅包括浮点数、整数和布尔值列。
新版本 1.5.0 中新增的方法。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba新版本 1.4.0 中新增的方法。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,没有被接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}新版本 1.4.0 中新增的方法。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参阅
与 NumPy 数组相同的方法。
pandas.Series.expanding
用 Series 数据调用 expanding。
pandas.DataFrame.expanding
用 DataFrame 调用 expanding。
pandas.Series.var
Series 的聚合变量。
pandas.DataFrame.var
DataFrame 的聚合变量。
注释
在Series.var()中使用的默认ddof为 1,而在numpy.var()中的默认ddof为 0。
滚动计算需要至少一个周期。
示例
>>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
>>> s.expanding(3).var()
0 NaN
1 NaN
2 0.333333
3 0.916667
4 0.800000
5 0.700000
6 0.619048
dtype: float64
pandas.core.window.expanding.Expanding.std
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.std.html
Expanding.std(ddof=1, numeric_only=False, engine=None, engine_kwargs=None)
计算扩展标准偏差。
参数:
ddofint,默认为 1
自由度增量。计算中使用的除数是 N - ddof,其中 N 表示元素数量。
numeric_onlybool,默认为 False
仅包括浮点数、整数和布尔列。
从版本 1.5.0 开始新增。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba从版本 1.4.0 开始新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}从版本 1.4.0 开始新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参见
NumPy 数组的等效方法。
pandas.Series.expanding
使用 Series 数据调用扩展。
pandas.DataFrame.expanding
使用 DataFrame 调用扩展。
pandas.Series.std
Series 的聚合 std。
pandas.DataFrame.std
DataFrame 的聚合 std。
注意事项
默认情况下,Series.std() 中使用的 ddof 默认值为 1,与 numpy.std() 中的默认 ddof 默认值 0 不同。
滚动计算需要至少一个周期。
示例
>>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
>>> s.expanding(3).std()
0 NaN
1 NaN
2 0.577350
3 0.957427
4 0.894427
5 0.836660
6 0.786796
dtype: float64
pandas.core.window.expanding.Expanding.min
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.min.html
Expanding.min(numeric_only=False, engine=None, engine_kwargs=None)
计算扩展的最小值。
参数:
numeric_only布尔值,默认为 False
仅包括浮点数、整数、布尔值列。
版本 1.5.0 中的新功能。
engine字符串,默认为 None
-
'cython':通过 C 扩展运行操作。 -
'numba':通过 Numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba版本 1.3.0 中的新功能。
engine_kwargs字典,默认为 None
-
对于
'cython'引擎,没有被接受的engine_kwargs。 -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}版本 1.3.0 中的新功能。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有np.float64数据类型。
请参见
pandas.Series.expanding
使用 Series 数据调用扩展。
pandas.DataFrame.expanding
使用 DataFrame 调用扩展。
pandas.Series.min
Series 的聚合最小值。
pandas.DataFrame.min
DataFrame 的聚合最小值。
注意事项
请参见 Numba 引擎和 Numba(JIT 编译)以获取 Numba 引擎的扩展文档和性能考虑。
示例
>>> ser = pd.Series([2, 3, 4, 1], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().min()
a 2.0
b 2.0
c 2.0
d 1.0
dtype: float64
pandas.core.window.expanding.Expanding.max
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.max.html
Expanding.max(numeric_only=False, engine=None, engine_kwargs=None)
计算扩展最大值。
参数:
numeric_onlybool,默认为 False
仅包含浮点数、整数、布尔值列。
自 1.5.0 版本新增。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba自 1.3.0 版本新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False}自 1.3.0 版本新增。
返回结果:
Series 或 DataFrame
返回类型与原始对象相同,具有 np.float64 dtype。
另请参见
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrame 调用 expanding。
pandas.Series.max
Series 的最大聚合。
pandas.DataFrame.max
DataFrame 的最大聚合。
注意事项
查看 Numba engine 和 Numba (JIT compilation)以获取有关 Numba 引擎的扩展文档和性能考虑。
示例
>>> ser = pd.Series([3, 2, 1, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().max()
a 3.0
b 3.0
c 3.0
d 4.0
dtype: float64
pandas.core.window.expanding.Expanding.corr
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.corr.html
Expanding.corr(other=None, pairwise=None, ddof=1, numeric_only=False)
计算扩展相关性。
参数:
otherSeries 或 DataFrame,可选
如果未提供,则默认为 self 并生成成对输出。
pairwise布尔值,默认为 None
如果为 False,则只使用 self 和 other 之间匹配的列,并且输出将是一个 DataFrame。如果为 True,则将计算所有成对组合,并且在 DataFrame 输入的情况下,输出将是一个 MultiIndexed DataFrame。在缺少元素的情况下,只有完整的成对观察结果才会被使用。
numeric_only布尔值,默认为 False
仅包括浮点数、整数、布尔值列。
在 1.5.0 版本中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有np.float64数据类型。
另请参见
cov
计算协方差的类似方法。
NumPy 的皮尔逊相关系数计算。
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrame 调用 expanding。
pandas.Series.corr
为 Series 聚合 corr。
pandas.DataFrame.corr
为 DataFrame 聚合 corr。
注意
该函数使用皮尔逊相关系数的定义(en.wikipedia.org/wiki/Pearson_correlation_coefficient)。
当未指定 other 时,输出将是 self 相关性(例如所有为 1),除了对于带有 pairwise 设置为 True 的 DataFrame 输入。
对于相等值序列的相关性,函数将返回NaN;这是 0/0 除法错误的结果。
当 pairwise 设置为 False 时,只使用 self 和 other 之间匹配的列。
当 pairwise 设置为 True 时,输出将是一个 MultiIndex DataFrame,原始索引在第一级,其他 DataFrame 列在第二级。
在缺少元素的情况下,只有完整的成对观察结果才会被使用。
示例
>>> ser1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser2 = pd.Series([10, 11, 13, 16], index=['a', 'b', 'c', 'd'])
>>> ser1.expanding().corr(ser2)
a NaN
b 1.000000
c 0.981981
d 0.975900
dtype: float64
pandas.core.window.expanding.Expanding.cov
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.cov.html
Expanding.cov(other=None, pairwise=None, ddof=1, numeric_only=False)
计算扩展样本协方差。
参数:
other Series 或 DataFrame,可选
如果未提供,则默认为 self 并生成成对输出。
pairwise 布尔值,默认为 None
如果为 False,则仅使用 self 和 other 之间匹配的列,并且输出将是一个 DataFrame。如果为 True,则将计算所有成对组合,并且在 DataFrame 输入的情况下输出将是一个 MultiIndexed DataFrame。在缺少元素的情况下,仅使用完整的成对观察。
ddof 整数,默认为 1
自由度差值。计算中使用的除数是 N - ddof,其中 N 表示元素数量。
numeric_only 布尔值,默认为 False
仅包括浮点数、整数、布尔值列。
1.5.0 版本中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为 np.float64。
另请参见
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrames 调用 expanding。
pandas.Series.cov
为 Series 聚合 cov。
pandas.DataFrame.cov
为 DataFrame 聚合 cov。
示例
>>> ser1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser2 = pd.Series([10, 11, 13, 16], index=['a', 'b', 'c', 'd'])
>>> ser1.expanding().cov(ser2)
a NaN
b 0.500000
c 1.500000
d 3.333333
dtype: float64
pandas.core.window.expanding.Expanding.skew
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.skew.html
Expanding.skew(numeric_only=False)
计算展开的无偏偏斜度。
参数:
numeric_only布尔值,默认为 False
仅包括浮点数、整数和布尔值列。
在版本 1.5.0 中新增。
返回:
系列或数据框
返回类型与原始对象相同,数据类型为np.float64。
另请参阅
概率密度的三阶矩。
pandas.Series.expanding
使用系列数据调用expanding。
pandas.DataFrame.expanding
使用数据框调用expanding。
pandas.Series.skew
系列的聚合偏斜度。
pandas.DataFrame.skew
数据框的聚合偏斜度。
注意事项
滚动计算需要至少三个周期。
示例
>>> ser = pd.Series([-1, 0, 2, -1, 2], index=['a', 'b', 'c', 'd', 'e'])
>>> ser.expanding().skew()
a NaN
b NaN
c 0.935220
d 1.414214
e 0.315356
dtype: float64
pandas.core.window.expanding.Expanding.kurt
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.kurt.html
Expanding.kurt(numeric_only=False)
在没有偏差的情况下计算展开的费舍尔峰度定义。
参数:
numeric_onlybool,默认为 False
只包含浮点型、整型和布尔型列。
自 1.5.0 版本新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参阅
参考 SciPy 方法。
pandas.Series.expanding
使用 Series 数据调用展开。
pandas.DataFrame.expanding
使用 DataFrame 调用展开。
pandas.Series.kurt
聚合 Series 的峰度。
pandas.DataFrame.kurt
聚合 DataFrame 的峰度。
注意事项
计算需要至少四个周期。
示例
下面的示例将展示一个滚动计算,窗口大小为四个,与使用 scipy.stats 的等价函数调用匹配。
>>> arr = [1, 2, 3, 4, 999]
>>> import scipy.stats
>>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}")
-1.200000
>>> print(f"{scipy.stats.kurtosis(arr, bias=False):.6f}")
4.999874
>>> s = pd.Series(arr)
>>> s.expanding(4).kurt()
0 NaN
1 NaN
2 NaN
3 -1.200000
4 4.999874
dtype: float64
pandas.core.window.expanding.Expanding.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.apply.html
Expanding.apply(func, raw=False, engine=None, engine_kwargs=None, args=None, kwargs=None)
计算扩展的自定义聚合函数。
参数:
func函数
如果raw=True,则必须从 ndarray 输入产生单个值,如果raw=False,则必须从 Series 产生单个值。还可以使用指定了engine='numba'的 Numba JIT 函数。
raw布尔值,默认为 False
-
False: 将每行或每列作为 Series 传递给函数。 -
True: 传递的函数将接收 ndarray 对象。如果只是应用 NumPy 的缩减函数,这将获得更好的性能。
engine字符串,默认为 None
-
'cython': 通过 cython 的 C 扩展运行滚动应用。 -
'numba': 通过 numba 编译的 JIT 代码运行滚动应用。仅当raw设置为True时可用。 -
None: 默认为'cython'或全局设置compute.use_numba
engine_kwargs字典,默认为 None
-
对于
'cython'引擎,没有接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须为True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False},将应用于func和apply滚动聚合。
args元组,默认为 None
传递到 func 的位置参数。
kwargs字典,默认为 None
传递到 func 的关键字参数。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参阅
使用 Series 数据调用 expanding。
使用 DataFrame 调用 expanding。
用于 Series 的聚合应用。
用于 DataFrame 的聚合应用。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
>>> ser.expanding().apply(lambda s: s.max() - 2 * s.min())
a -1.0
b 0.0
c 1.0
d 2.0
dtype: float64
pandas.core.window.expanding.Expanding.aggregate
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.aggregate.html
Expanding.aggregate(func, *args, **kwargs)
使用一个或多个操作对指定轴上的数据进行聚合。
参数:
func 函数、字符串、列表或字典
用于聚合数据的函数。如果是函数,必须能够在传递 Series/Dataframe 时工作,或者能够传递给 Series/Dataframe.apply。
接受的组合有:
-
函数
-
字符串函数名称
-
函数和/或函数名称的列表,例如
[np.sum, 'mean'] -
轴标签 -> 函数、函数名称或此类列表的字典。
*args
传递给 func 的位置参数。
**kwargs
传递给 func 的关键字参数。
返回:
scalar、Series 或 DataFrame
返回可以是:
-
scalar:当 Series.agg 被单个函数调用时
-
Series:当 DataFrame.agg 被单个函数调用时
-
DataFrame:当 DataFrame.agg 被多个函数调用时
另请参阅
pandas.DataFrame.aggregate
类似的 DataFrame 方法。
pandas.Series.aggregate
类似的序列方法。
注意事项
聚合操作始终在一个轴上执行,可以是索引(默认)或列轴。此行为与 numpy 聚合函数(mean、median、prod、sum、std、var)不同,numpy 聚合函数的默认值是计算平坦数组的聚合,例如,numpy.mean(arr_2d) 而不是 numpy.mean(arr_2d, axis=0)。
agg 是 aggregate 的别名。请使用该别名。
对传递的对象进行突变的函数可能会产生意外行为或错误,并且不受支持。有关更多详细信息,请参见 使用用户定义函数 (UDF) 方法进行突变。
传递的用户定义函数将传递一个 Series 进行评估。
示例
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
>>> df
A B C
0 1 4 7
1 2 5 8
2 3 6 9
>>> df.ewm(alpha=0.5).mean()
A B C
0 1.000000 4.000000 7.000000
1 1.666667 4.666667 7.666667
2 2.428571 5.428571 8.428571
pandas.core.window.expanding.Expanding.quantile
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.quantile.html
Expanding.quantile(q, interpolation='linear', numeric_only=False)
计算扩展的分位数。
参数:
分位数float
要计算的分位数。0 <= quantile <= 1。
从版本 2.1.0 开始已弃用:将来的版本中将重命名为‘q’。
插值
这个可选参数指定了在所需的分位数落在两个数据点 i 和 j 之间时要使用的插值方法:
- 线性插值:i + (j - i) * fraction,其中 fraction 是被 i 和 j 包围的索引的小数部分。
- 低端插值:i。
- 高端插值:j。
- 最近邻插值:取最近的 i 或 j。
- 中点插值:(i + j) / 2。
numeric_onlybool,默认为 False
只包含 float、int、boolean 列。
版本 1.5.0 中的新增内容。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为 np.float64 dtype。
另请参阅
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrame 调用 expanding。
pandas.Series.quantile
Series 的聚合分位数。
pandas.DataFrame.quantile
DataFrame 的聚合分位数。
示例
>>> ser = pd.Series([1, 2, 3, 4, 5, 6], index=['a', 'b', 'c', 'd', 'e', 'f'])
>>> ser.expanding(min_periods=4).quantile(.25)
a NaN
b NaN
c NaN
d 1.75
e 2.00
f 2.25
dtype: float64
pandas.core.window.expanding.Expanding.sem
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.sem.html
Expanding.sem(ddof=1, numeric_only=False)
计算展开平均标准误差。
参数:
ddofint,默认为 1
自由度增量。计算中使用的除数为N - ddof,其中N表示元素数。
numeric_onlybool,默认为 False
仅包括 float、int 和 boolean 列。
自版本 1.5.0 起新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,为np.float64类型。
另请参见
pandas.Series.expanding
使用 Series 数据调用 expanding。
pandas.DataFrame.expanding
使用 DataFrame 调用 expanding。
pandas.Series.sem
为 Series 聚合 sem。
pandas.DataFrame.sem
为 DataFrame 聚合 sem。
注意事项
计算需要至少一个周期。
示例
>>> s = pd.Series([0, 1, 2, 3])
>>> s.expanding().sem()
0 NaN
1 0.707107
2 0.707107
3 0.745356
dtype: float64
pandas.core.window.expanding.Expanding.rank
pandas.pydata.org/docs/reference/api/pandas.core.window.expanding.Expanding.rank.html
Expanding.rank(method='average', ascending=True, pct=False, numeric_only=False)
计算扩展排名。
自 1.4.0 版开始的新功能。
参数:
method {'average', 'min', 'max'},默认为 'average'
如何对具有相同值的记录组进行排名(即并列):
-
average:组的平均排名
-
min:组内最低排名
-
max:组内最高排名
ascending 布尔值,默认为 True
元素是否应以升序排名。
pct 布尔值,默认为 False
是否以百分位形式显示返回的排名。
numeric_only 布尔值,默认为 False
仅包括浮点数、整数、布尔值列。
自 1.5.0 版开始的新功能。
返回:
序列或 DataFrame
返回类型与原始对象相同,数据类型为 np.float64。
另请参阅
使用 Series 数据调用扩展功能。
使用 DataFrame 调用扩展功能。
聚合序列的排名。
聚合 DataFrame 的排名。
示例
>>> s = pd.Series([1, 4, 2, 3, 5, 3])
>>> s.expanding().rank()
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 3.5
dtype: float64
>>> s.expanding().rank(method="max")
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 4.0
dtype: float64
>>> s.expanding().rank(method="min")
0 1.0
1 2.0
2 2.0
3 3.0
4 5.0
5 3.0
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.mean
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.mean.html
ExponentialMovingWindow.mean(numeric_only=False, engine=None, engine_kwargs=None)
计算 ewm(指数加权平均)的平均值。
参数:
numeric_onlybool, default False
仅包括浮点数、整数、布尔值列。
新版本 1.5.0。
enginestr, default None
-
'cython': 通过 cython 的 C 扩展运行操作。 -
'numba': 通过 numba 的 JIT 编译代码运行操作。 -
None: 默认为'cython'或全局设置compute.use_numba新版本 1.3.0。
engine_kwargsdict, default None
-
对于
'cython'引擎,没有被接受的engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython,nogil和parallel字典键。 值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}新版本 1.3.0。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为np.float64。
另请参见
pandas.Series.ewm
用 Series 数据调用 ewm。
pandas.DataFrame.ewm
用 DataFrame 调用 ewm。
pandas.Series.mean
用于 Series 的平均聚合。
pandas.DataFrame.mean
DataFrame 的平均聚合。
注释
参见 Numba 引擎和 Numba(JIT 编译)以获取扩展文档和 Numba 引擎的性能考虑。
示例
>>> ser = pd.Series([1, 2, 3, 4])
>>> ser.ewm(alpha=.2).mean()
0 1.000000
1 1.555556
2 2.147541
3 2.775068
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.sum
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.sum.html
ExponentialMovingWindow.sum(numeric_only=False, engine=None, engine_kwargs=None)
计算 ewm(指数加权移动)求和。
参数:
numeric_onlybool,默认为 False
仅包括 float、int、boolean 列。
自版本 1.5.0 新增。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行操作。 -
'numba':通过 numba 的 JIT 编译代码运行操作。 -
None:默认为'cython'或全局设置compute.use_numba自版本 1.3.0 新增。
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,该引擎可以接受nopython、nogil和parallel字典键。其值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False}自版本 1.3.0 新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,dtype 为 np.float64。
另请参见
pandas.Series.ewm
以 Series 数据调用 ewm。
pandas.DataFrame.ewm
以 DataFrame 调用 ewm。
pandas.Series.sum
Series 的聚合求和。
pandas.DataFrame.sum
DataFrame 的聚合求和。
注意
参见 Numba 引擎和 Numba(JIT 编译)以获取 Numba 引擎的扩展文档和性能考虑。
示例
>>> ser = pd.Series([1, 2, 3, 4])
>>> ser.ewm(alpha=.2).sum()
0 1.000
1 2.800
2 5.240
3 8.192
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.std
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.std.html
ExponentialMovingWindow.std(bias=False, numeric_only=False)
计算指数加权移动平均(ewm)标准差。
参数:
bias布尔型,默认为 False
使用标准的估计偏差校正。
numeric_only布尔型,默认为 False
仅包括浮点数、整数和布尔值列。
自 1.5.0 版本新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为np.float64。
另请参阅
pandas.Series.ewm
使用 Series 数据调用 ewm。
pandas.DataFrame.ewm
使用 DataFrame 调用 ewm。
pandas.Series.std
为 Series 聚合 std。
pandas.DataFrame.std
为 DataFrame 聚合 std。
示例
>>> ser = pd.Series([1, 2, 3, 4])
>>> ser.ewm(alpha=.2).std()
0 NaN
1 0.707107
2 0.995893
3 1.277320
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.var
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.var.html
ExponentialMovingWindow.var(bias=False, numeric_only=False)
计算 ewm(指数加权矩)方差。
参数:
bias 布尔值,默认为 False
使用标准的估计偏差校正。
numeric_only 布尔值,默认为 False
仅包括浮点数、整数、布尔值列。
版本 1.5.0 中的新功能。
返回:
Series 或 DataFrame
返回类型与原始对象相同,数据类型为 np.float64。
另请参阅
pandas.Series.ewm
使用 Series 数据调用 ewm 方法。
pandas.DataFrame.ewm
调用 DataFrames 的 ewm 方法。
pandas.Series.var
对 Series 进行聚合 var。
pandas.DataFrame.var
对 DataFrame 进行聚合 var。
示例
>>> ser = pd.Series([1, 2, 3, 4])
>>> ser.ewm(alpha=.2).var()
0 NaN
1 0.500000
2 0.991803
3 1.631547
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.corr
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.corr.html
ExponentialMovingWindow.corr(other=None, pairwise=None, numeric_only=False)
计算 ewm(指数加权矩)样本相关性。
参数:
otherSeries 或 DataFrame,可选
如果未提供,则默认为 self 并生成成对输出。
pairwisebool,默认为 None
如果为 False,则仅使用 self 和 other 之间匹配的列,并且输出将是一个 DataFrame。如果为 True,则将计算所有成对组合,并且在 DataFrame 输入的情况下,输出将是一个 MultiIndex DataFrame。在缺少元素的情况下,仅使用完整的成对观察。
numeric_onlybool,默认为 False
仅包括浮点数、整数、布尔值列。
在版本 1.5.0 中新增。
返回:
Series 或 DataFrame
返回类型与原始对象相同,具有 np.float64 数据类型。
另请参阅
pandas.Series.ewm
使用 Series 数据调用 ewm。
pandas.DataFrame.ewm
使用 DataFrame 调用 ewm。
pandas.Series.corr
为 Series 聚合 corr。
pandas.DataFrame.corr
为 DataFrame 聚合 corr。
示例
>>> ser1 = pd.Series([1, 2, 3, 4])
>>> ser2 = pd.Series([10, 11, 13, 16])
>>> ser1.ewm(alpha=.2).corr(ser2)
0 NaN
1 1.000000
2 0.982821
3 0.977802
dtype: float64
pandas.core.window.ewm.ExponentialMovingWindow.cov
原文:
pandas.pydata.org/docs/reference/api/pandas.core.window.ewm.ExponentialMovingWindow.cov.html
ExponentialMovingWindow.cov(other=None, pairwise=None, bias=False, numeric_only=False)
计算 ewm(指数加权矩)样本协方差。
参数:
other Series 或 DataFrame,可选
如果未提供,则默认为 self 并生成成对的输出。
pairwise 布尔型,默认为 None
如果为 False,则仅使用 self 和 other 之间的匹配列,并且输出将是 DataFrame。如果为 True,则将计算所有成对组合,并且输出将是 DataFrame 输入的 MultiIndex DataFrame。在缺少元素的情况下,只使用完整的成对观测值。
bias 布尔型,默认为 False
使用标准估计偏差校正。
numeric_only 布尔型,默认为 False
仅包括浮点、整数和布尔列。
版本 1.5.0 中的新功能。
返回:
Series 或 DataFrame
返回类型与原始对象相同,类型为 np.float64。
另请参阅
pandas.Series.ewm
使用 Series 数据调用 ewm。
pandas.DataFrame.ewm
使用 DataFrames 调用 ewm。
pandas.Series.cov
对 Series 进行聚合 cov。
pandas.DataFrame.cov
对 DataFrame 进行聚合 cov。
示例
>>> ser1 = pd.Series([1, 2, 3, 4])
>>> ser2 = pd.Series([10, 11, 13, 16])
>>> ser1.ewm(alpha=.2).cov(ser2)
0 NaN
1 0.500000
2 1.524590
3 3.408836
dtype: float64
pandas.api.indexers.BaseIndexer
原文:
pandas.pydata.org/docs/reference/api/pandas.api.indexers.BaseIndexer.html
class pandas.api.indexers.BaseIndexer(index_array=None, window_size=0, **kwargs)
用于窗口边界计算的基类。
示例
>>> from pandas.api.indexers import BaseIndexer
>>> class CustomIndexer(BaseIndexer):
... def get_window_bounds(self, num_values, min_periods, center, closed, step):
... start = np.empty(num_values, dtype=np.int64)
... end = np.empty(num_values, dtype=np.int64)
... for i in range(num_values):
... start[i] = i
... end[i] = i + self.window_size
... return start, end
>>> df = pd.DataFrame({"values": range(5)})
>>> indexer = CustomIndexer(window_size=2)
>>> df.rolling(indexer).sum()
values
0 1.0
1 3.0
2 5.0
3 7.0
4 4.0
方法
get_window_bounds([num_values, min_periods, ...]) |
计算窗口的边界。 |
|---|
pandas.api.indexers.FixedForwardWindowIndexer
原文:
pandas.pydata.org/docs/reference/api/pandas.api.indexers.FixedForwardWindowIndexer.html
class pandas.api.indexers.FixedForwardWindowIndexer(index_array=None, window_size=0, **kwargs)
创建包含当前行的固定长度窗口的窗口边界。
示例
>>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
>>> df
B
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
>>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
>>> df.rolling(window=indexer, min_periods=1).sum()
B
0 1.0
1 3.0
2 2.0
3 4.0
4 4.0
方法
get_window_bounds([num_values, min_periods, ...]) |
计算窗口的边界。 |
|---|
pandas.api.indexers.VariableOffsetWindowIndexer
原文:
pandas.pydata.org/docs/reference/api/pandas.api.indexers.VariableOffsetWindowIndexer.html
class pandas.api.indexers.VariableOffsetWindowIndexer(index_array=None, window_size=0, index=None, offset=None, **kwargs)
基于非固定偏移(例如工作日)计算窗口边界。
示例
>>> from pandas.api.indexers import VariableOffsetWindowIndexer
>>> df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10))
>>> offset = pd.offsets.BDay(1)
>>> indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset)
>>> df
0
2020-01-01 0
2020-01-02 1
2020-01-03 2
2020-01-04 3
2020-01-05 4
2020-01-06 5
2020-01-07 6
2020-01-08 7
2020-01-09 8
2020-01-10 9
>>> df.rolling(indexer).sum()
0
2020-01-01 0.0
2020-01-02 1.0
2020-01-03 2.0
2020-01-04 3.0
2020-01-05 7.0
2020-01-06 12.0
2020-01-07 6.0
2020-01-08 7.0
2020-01-09 8.0
2020-01-10 9.0
方法
get_window_bounds([num_values, min_periods, ...]) |
计算窗口的边界。 |
|---|
GroupBy
pandas.api.typing.DataFrameGroupBy 和 pandas.api.typing.SeriesGroupBy 实例是由 groupby 调用 pandas.DataFrame.groupby() 和 pandas.Series.groupby() 返回的。
索引、迭代
DataFrameGroupBy.__iter__() |
分组迭代器。 |
|---|---|
SeriesGroupBy.__iter__() |
分组迭代器。 |
DataFrameGroupBy.groups |
字典 {组名 -> 组标签}。 |
SeriesGroupBy.groups |
字典 {组名 -> 组标签}。 |
DataFrameGroupBy.indices |
字典 {组名 -> 组索引}。 |
SeriesGroupBy.indices |
字典 {组名 -> 组索引}。 |
DataFrameGroupBy.get_group(name[, obj]) |
使用提供的名称构造组内的 DataFrame。 |
SeriesGroupBy.get_group(name[, obj]) |
使用提供的名称构造组内的 DataFrame。 |
Grouper(*args, **kwargs) |
Grouper 允许用户为对象指定分组指令。 |
函数应用助手
NamedAgg(column, aggfunc) |
用于具有对输出列名称的控制的特定列聚合的辅助程序。 |
|---|
函数应用
SeriesGroupBy.apply(func, *args, **kwargs) |
对函数 func 分组应用,并将结果合并在一起。 |
|---|---|
DataFrameGroupBy.apply |
逐组应用函数 func,并将结果组合在一起。 |
SeriesGroupBy.agg |
使用一个或多个操作聚合指定轴上的数据。 |
DataFrameGroupBy.agg |
使用一个或多个操作聚合指定轴上的数据。 |
SeriesGroupBy.aggregate |
使用一个或多个操作聚合指定轴上的数据。 |
DataFrameGroupBy.aggregate |
使用一个或多个操作聚合指定轴上的数据。 |
SeriesGroupBy.transform |
在每个组上调用产生相同索引的 Series 的函数。 |
DataFrameGroupBy.transform |
在每个组上调用产生相同索引的 DataFrame 的函数。 |
SeriesGroupBy.pipe |
对该 GroupBy 对象应用带有参数的 func,并返回其结果。 |
DataFrameGroupBy.pipe |
对该 GroupBy 对象应用带有参数的 func,并返回其结果。 |
DataFrameGroupBy.filter |
过滤不符合条件的组中的元素。 |
SeriesGroupBy.filter |
过滤不符合条件的组中的元素。 |
DataFrameGroupBy 计算 / 描述性统计
DataFrameGroupBy.all([skipna]) |
如果组中所有值为真,则返回 True,否则返回 False。 |
|---|---|
DataFrameGroupBy.any([skipna]) |
如果组中任何值为真,则返回 True,否则返回 False。 |
DataFrameGroupBy.bfill([limit]) |
后向填充值。 |
DataFrameGroupBy.corr([method, min_periods, ...]) |
计算列的成对相关性,不包括 NA/null 值。 |
DataFrameGroupBy.corrwith(other[, axis, ...]) |
计算成对相关性。 |
DataFrameGroupBy.count() |
计算组的计数,不包括缺失值。 |
DataFrameGroupBy.cov([min_periods, ddof, ...]) |
计算列的成对协方差,不包括 NA/null 值。 |
DataFrameGroupBy.cumcount([ascending]) |
为每个组中的每个项目编号,编号从 0 到该组的长度 - 1。 |
DataFrameGroupBy.cummax([axis, numeric_only]) |
每个分组的累积最大值。 |
DataFrameGroupBy.cummin([axis, numeric_only]) |
每个分组的累积最小值。 |
DataFrameGroupBy.cumprod([axis]) |
每个分组的累积乘积。 |
DataFrameGroupBy.cumsum([axis]) |
每个分组的累积总和。 |
DataFrameGroupBy.describe([percentiles, ...]) |
生成描述性统计。 |
DataFrameGroupBy.diff([periods, axis]) |
元素的第一个离散差异。 |
DataFrameGroupBy.ffill([limit]) |
向前填充值。 |
DataFrameGroupBy.fillna([value, method, ...]) |
(已弃用)使用指定方法填充组内的 NA/NaN 值。 |
DataFrameGroupBy.first([numeric_only, ...]) |
计算每个组内每列的第一个条目。 |
DataFrameGroupBy.head([n]) |
返回每个组的前 n 行。 |
DataFrameGroupBy.idxmax([axis, skipna, ...]) |
返回请求轴上最大值的第一个出现位置的索引。 |
DataFrameGroupBy.idxmin([axis, skipna, ...]) |
返回请求轴上最小值的第一个出现位置的索引。 |
DataFrameGroupBy.last([numeric_only, ...]) |
计算每个组内每列的最后一个条目。 |
DataFrameGroupBy.max([numeric_only, ...]) |
计算组值的最大值。 |
DataFrameGroupBy.mean([numeric_only, ...]) |
计算组的平均值,不包括缺失值。 |
DataFrameGroupBy.median([numeric_only]) |
计算组的中位数,不包括缺失值。 |
DataFrameGroupBy.min([numeric_only, ...]) |
计算组值的最小值。 |
DataFrameGroupBy.ngroup([ascending]) |
将每个组从 0 编号到组数 - 1。 |
DataFrameGroupBy.nth |
如果 n 是整数,则从每个组中取第 n 行,否则取一部分行。 |
DataFrameGroupBy.nunique([dropna]) |
返回每个位置上唯一元素的计数的 DataFrame。 |
DataFrameGroupBy.ohlc() |
计算组的开盘价、最高价、最低价和收盘价值,不包括缺失值。 |
DataFrameGroupBy.pct_change([periods, ...]) |
计算每个值相对于组中前一个条目的百分比变化。 |
DataFrameGroupBy.prod([numeric_only, min_count]) |
计算组值的乘积。 |
DataFrameGroupBy.quantile([q, ...]) |
返回给定分位数处的组值,类似于 numpy.percentile。 |
DataFrameGroupBy.rank([method, ascending, ...]) |
在每个组内提供值的排名。 |
DataFrameGroupBy.resample(rule, *args[, ...]) |
在使用 TimeGrouper 时提供重新采样。 |
DataFrameGroupBy.rolling(*args, **kwargs) |
返回一个滚动分组器,为每个组提供滚动功能。 |
DataFrameGroupBy.sample([n, frac, replace, ...]) |
返回每个组中的随机样本项。 |
DataFrameGroupBy.sem([ddof, numeric_only]) |
计算组的平均标准误差,排除缺失值。 |
DataFrameGroupBy.shift([periods, freq, ...]) |
将每个组的观察值按周期移动。 |
DataFrameGroupBy.size() |
计算组大小。 |
DataFrameGroupBy.skew([axis, skipna, ...]) |
返回组内的无偏偏度。 |
DataFrameGroupBy.std([ddof, engine, ...]) |
计算组的标准差,排除缺失值。 |
DataFrameGroupBy.sum([numeric_only, ...]) |
计算组值的总和。 |
DataFrameGroupBy.var([ddof, engine, ...]) |
计算组的方差,排除缺失值。 |
DataFrameGroupBy.tail([n]) |
返回每个组的最后 n 行。 |
DataFrameGroupBy.take(indices[, axis]) |
返回每个组中给定 位置 索引的元素。 |
DataFrameGroupBy.value_counts([subset, ...]) |
返回包含唯一行计数的 Series 或 DataFrame。 |
SeriesGroupBy 计算 / 描述统计信息
SeriesGroupBy.all([skipna]) |
如果组内所有值都为真,则返回 True,否则返回 False。 |
|---|---|
SeriesGroupBy.any([skipna]) |
如果组内任何值都为真,则返回 True,否则返回 False。 |
SeriesGroupBy.bfill |
向后填充值。 |
SeriesGroupBy.corr(other[, method, min_periods]) |
与其他 Series 计算相关性,不包括缺失值。 |
SeriesGroupBy.count |
计算组的计数,不包括缺失值。 |
SeriesGroupBy.cov(other[, min_periods, ddof]) |
与 Series 计算协方差,不包括缺失值。 |
SeriesGroupBy.cumcount |
在每个组中对每个项目进行编号,从 0 到该组的长度-1。 |
SeriesGroupBy.cummax |
每个组的累积最大值。 |
SeriesGroupBy.cummin |
每个组的累积最小值。 |
SeriesGroupBy.cumprod |
每个组的累积乘积。 |
SeriesGroupBy.cumsum |
每个组的累积和。 |
SeriesGroupBy.describe |
生成描述性统计。 |
SeriesGroupBy.diff |
元素的第一个离散差异。 |
SeriesGroupBy.ffill |
向前填充值。 |
SeriesGroupBy.fillna |
(已弃用) 使用指定方法填充组内的 NA/NaN 值。 |
SeriesGroupBy.first |
计算每个组中每列的第一个条目。 |
SeriesGroupBy.head |
返回每个组的前 n 行。 |
SeriesGroupBy.last |
计算每个组中每列的最后一个条目。 |
SeriesGroupBy.idxmax |
返回最大值的行标签。 |
SeriesGroupBy.idxmin |
返回最小值的行标签。 |
SeriesGroupBy.is_monotonic_increasing |
返回每个组的值是否单调递增。 |
SeriesGroupBy.is_monotonic_decreasing |
返回每个组的值是否单调递减。 |
SeriesGroupBy.max |
计算组值的最大值。 |
SeriesGroupBy.mean |
计算组的均值,不包括缺失值。 |
SeriesGroupBy.median |
计算组的中位数,不包括缺失值。 |
SeriesGroupBy.min |
计算组值的最小值。 |
SeriesGroupBy.ngroup |
为每个组编号,从 0 到组数-1。 |
SeriesGroupBy.nlargest([n, keep]) |
返回最大的 n 个元素。 |
SeriesGroupBy.nsmallest([n, keep]) |
返回最小的 n 个元素。 |
SeriesGroupBy.nth |
如果 n 是 int,则从每个组中取出第 n 行,否则是行的子集。 |
SeriesGroupBy.nunique([dropna]) |
返回组中唯一元素的数量。 |
SeriesGroupBy.unique() |
返回每个组的唯一值。 |
SeriesGroupBy.ohlc() |
计算组的开盘价、最高价、最低价和收盘价,不包括缺失值。 |
SeriesGroupBy.pct_change([periods, ...]) |
计算每个值相对于组内上一个条目的百分比变化。 |
SeriesGroupBy.prod([numeric_only, min_count]) |
计算组值的乘积。 |
SeriesGroupBy.quantile([q, interpolation, ...]) |
返回给定分位数处的组值,类似于 numpy.percentile。 |
SeriesGroupBy.rank([method, ascending, ...]) |
提供每个组内值的排名。 |
SeriesGroupBy.resample(rule, *args[, ...]) |
在使用 TimeGrouper 时提供重新采样。 |
SeriesGroupBy.rolling(*args, **kwargs) |
返回一个滚动 grouper,为每个组提供滚动功能。 |
SeriesGroupBy.sample([n, frac, replace, ...]) |
从每个组中返回随机样本项。 |
SeriesGroupBy.sem([ddof, numeric_only]) |
计算组的平均标准误差,排除缺失值。 |
SeriesGroupBy.shift([periods, freq, axis, ...]) |
将每个组向前或向后移动 periods 次观察。 |
SeriesGroupBy.size() |
计算组大小。 |
SeriesGroupBy.skew([axis, skipna, numeric_only]) |
返回组内无偏斜度。 |
SeriesGroupBy.std([ddof, engine, ...]) |
计算组的标准差,排除缺失值。 |
SeriesGroupBy.sum([numeric_only, min_count, ...]) |
计算组值的总和。 |
SeriesGroupBy.var([ddof, engine, ...]) |
计算组的方差,排除缺失值。 |
SeriesGroupBy.tail([n]) |
返回每个组的最后 n 行。 |
SeriesGroupBy.take(indices[, axis]) |
返回每个组中给定位置索引的元素。 |
SeriesGroupBy.value_counts([normalize, ...]) |
绘图和可视化
DataFrameGroupBy.boxplot([subplots, column, ...]) |
从 DataFrameGroupBy 数据绘制箱线图。 |
|---|---|
DataFrameGroupBy.hist([column, by, grid, ...]) |
绘制 DataFrame 的列的直方图。 |
SeriesGroupBy.hist([by, ax, grid, ...]) |
使用 matplotlib 绘制输入 Series 的直方图。 |
DataFrameGroupBy.plot |
绘制 Series 或 DataFrame 的图表。 |
SeriesGroupBy.plot |
绘制 Series 或 DataFrame 的图表。 |
索引、迭代
DataFrameGroupBy.__iter__() |
分组迭代器。 |
|---|---|
SeriesGroupBy.__iter__() |
分组迭代器。 |
DataFrameGroupBy.groups |
字典 {分组名称 -> 分组标签}。 |
SeriesGroupBy.groups |
字典 {分组名称 -> 分组标签}。 |
DataFrameGroupBy.indices |
字典 {分组名称 -> 分组索引}。 |
SeriesGroupBy.indices |
字典 {分组名称 -> 分组索引}。 |
DataFrameGroupBy.get_group(name[, obj]) |
根据提供的名称构造组的 DataFrame。 |
SeriesGroupBy.get_group(name[, obj]) |
根据提供的名称构造组的 DataFrame。 |
Grouper(*args, **kwargs) |
Grouper 允许用户为对象指定分组指令。 |
功能应用助手
NamedAgg(column, aggfunc) |
用于具有对输出列名称的控制的列特定聚合的辅助工具。 |
|---|
功能应用
SeriesGroupBy.apply(func, *args, **kwargs) |
逐组应用函数 func 并将结果组合在一起。 |
|---|---|
DataFrameGroupBy.apply(func, *args[, ...]) |
逐组应用函数 func 并将结果组合在一起。 |
SeriesGroupBy.agg([func, engine, engine_kwargs]) |
使用一个或多个操作对指定轴进行聚合。 |
DataFrameGroupBy.agg([func, engine, ...]) |
使用一个或多个操作对指定轴进行聚合。 |
SeriesGroupBy.aggregate([func, engine, ...]) |
使用一个或多个操作对指定轴进行聚合。 |
DataFrameGroupBy.aggregate([func, engine, ...]) |
使用一个或多个操作对指定轴进行聚合。 |
SeriesGroupBy.transform(func, *args[, ...]) |
在每个分组上调用产生具有相同索引的 Series 的函数。 |
DataFrameGroupBy.transform(func, *args[, ...]) |
在每个分组上调用产生具有相同索引的 DataFrame 的函数。 |
SeriesGroupBy.pipe(func, *args, **kwargs) |
对该 GroupBy 对象应用带有参数的 func,并返回其结果。 |
DataFrameGroupBy.pipe(func, *args, **kwargs) |
对该 GroupBy 对象应用带有参数的 func,并返回其结果。 |
DataFrameGroupBy.filter(func[, dropna]) |
从不满足条件的组中筛选元素。 |
SeriesGroupBy.filter(func[, dropna]) |
从不满足条件的组中筛选元素。 |
DataFrameGroupBy 计算 / 描述统计
DataFrameGroupBy.all([skipna]) |
如果组中的所有值为真则返回 True,否则返回 False。 |
|---|---|
DataFrameGroupBy.any([skipna]) |
如果组中的任何值为真则返回 True,否则返回 False。 |
DataFrameGroupBy.bfill([limit]) |
向后填充值。 |
DataFrameGroupBy.corr([method, min_periods, ...]) |
计算列的成对相关性,排除 NA/null 值。 |
DataFrameGroupBy.corrwith(other[, axis, ...]) |
计算成对相关性。 |
DataFrameGroupBy.count() |
计算组的计数,排除缺失值。 |
DataFrameGroupBy.cov([min_periods, ddof, ...]) |
计算列的成对协方差,排除 NA/null 值。 |
DataFrameGroupBy.cumcount([ascending]) |
对每个组中的项进行编号,编号从 0 到该组长度 - 1。 |
DataFrameGroupBy.cummax([axis, numeric_only]) |
每个组的累积最大值。 |
DataFrameGroupBy.cummin([axis, numeric_only]) |
每个组的累积最小值。 |
DataFrameGroupBy.cumprod([axis]) |
每个组的累积乘积。 |
DataFrameGroupBy.cumsum |
每个组的累积和。 |
DataFrameGroupBy.describe |
生成描述性统计信息。 |
DataFrameGroupBy.diff |
元素的第一个离散差异。 |
DataFrameGroupBy.ffill |
向前填充值。 |
DataFrameGroupBy.fillna |
(已弃用)使用组内指定方法填充 NA/NaN 值。 |
DataFrameGroupBy.first |
计算每个组内每列的第一个条目。 |
DataFrameGroupBy.head |
返回每个组的前 n 行。 |
DataFrameGroupBy.idxmax |
返回请求轴上最大值的第一次出现的索引。 |
DataFrameGroupBy.idxmin |
返回请求轴上最小值的第一次出现的索引。 |
DataFrameGroupBy.last |
计算每个组内每列的最后一个条目。 |
DataFrameGroupBy.max |
计算组值的最大值。 |
DataFrameGroupBy.mean |
计算组的均值,不包括缺失值。 |
DataFrameGroupBy.median([numeric_only]) |
计算每个组的中位数,排除缺失值。 |
DataFrameGroupBy.min([numeric_only, ...]) |
计算组值的最小值。 |
DataFrameGroupBy.ngroup([ascending]) |
从 0 到组数 - 1 对每个组进行编号。 |
DataFrameGroupBy.nth |
如果 n 是整数,则从每个组中获取第 n 行,否则获取行的子集。 |
DataFrameGroupBy.nunique([dropna]) |
返回每个位置上唯一元素的计数的 DataFrame。 |
DataFrameGroupBy.ohlc() |
计算组的开盘价、最高价、最低价和收盘价,排除缺失值。 |
DataFrameGroupBy.pct_change([periods, ...]) |
计算每个值相对于组内上一个条目的百分比变化。 |
DataFrameGroupBy.prod([numeric_only, min_count]) |
计算组值的乘积。 |
DataFrameGroupBy.quantile([q, ...]) |
返回给定分位数处的组值,类似于 numpy.percentile。 |
DataFrameGroupBy.rank([method, ascending, ...]) |
提供每个组内值的排名。 |
DataFrameGroupBy.resample(rule, *args[, ...]) |
在使用 TimeGrouper 时提供重新采样。 |
DataFrameGroupBy.rolling(*args, **kwargs) |
返回滚动分组器,为每个组提供滚动功能。 |
DataFrameGroupBy.sample([n, frac, replace, ...]) |
返回每个组的随机样本。 |
DataFrameGroupBy.sem([ddof, numeric_only]) |
计算组的均值标准误差,排除缺失值。 |
DataFrameGroupBy.shift([periods, freq, ...]) |
将每个组的观测值向前或向后移动。 |
DataFrameGroupBy.size() |
计算组大小。 |
DataFrameGroupBy.skew([axis, skipna, ...]) |
返回组内无偏斜。 |
DataFrameGroupBy.std([ddof, engine, ...]) |
计算组的标准差,排除缺失值。 |
DataFrameGroupBy.sum([numeric_only, ...]) |
计算组值的总和。 |
DataFrameGroupBy.var([ddof, engine, ...]) |
计算组的方差,排除缺失值。 |
DataFrameGroupBy.tail([n]) |
返回每个组的最后 n 行。 |
DataFrameGroupBy.take(indices[, axis]) |
返回每个分组中给定 位置 索引的元素。 |
DataFrameGroupBy.value_counts([subset, ...]) |
返回包含唯一行计数的 Series 或 DataFrame。 |
SeriesGroupBy 计算 / 描述统计
SeriesGroupBy.all([skipna]) |
如果组中所有值都为真,则返回 True,否则返回 False。 |
|---|---|
SeriesGroupBy.any([skipna]) |
如果组中有任何值为真,则返回 True,否则返回 False。 |
SeriesGroupBy.bfill([limit]) |
向后填充值。 |
SeriesGroupBy.corr(other[, method, min_periods]) |
与其他 Series 计算相关性,不包括缺失值。 |
SeriesGroupBy.count() |
计算组的数量,不包括缺失值。 |
SeriesGroupBy.cov(other[, min_periods, ddof]) |
与 Series 计算协方差,不包括缺失值。 |
SeriesGroupBy.cumcount([ascending]) |
对每个组中的每个项目进行编号,从 0 到该组的长度-1。 |
SeriesGroupBy.cummax([axis, numeric_only]) |
每个组的累积最大值。 |
SeriesGroupBy.cummin([axis, numeric_only]) |
每个组的累积最小值。 |
SeriesGroupBy.cumprod([axis]) |
每个组的累积乘积。 |
SeriesGroupBy.cumsum([axis]) |
每个组的累积总和。 |
SeriesGroupBy.describe([percentiles, ...]) |
生成描述性统计。 |
SeriesGroupBy.diff([periods, axis]) |
元素的第一个离散差异。 |
SeriesGroupBy.ffill([limit]) |
向前填充值。 |
SeriesGroupBy.fillna([value, method, axis, ...]) |
(已弃用)使用指定的方法填充组内的 NA/NaN 值。 |
SeriesGroupBy.first([numeric_only, ...]) |
计算每个组内每列的第一个条目。 |
SeriesGroupBy.head([n]) |
返回每个组的前 n 行。 |
SeriesGroupBy.last([numeric_only, ...]) |
计算每个组内每列的最后一个条目。 |
SeriesGroupBy.idxmax([axis, skipna]) |
返回最大值的行标签。 |
SeriesGroupBy.idxmin([axis, skipna]) |
返回最小值的行标签。 |
SeriesGroupBy.is_monotonic_increasing |
返回每个组的值是否单调递增。 |
SeriesGroupBy.is_monotonic_decreasing |
返回每个组的值是否单调递减。 |
SeriesGroupBy.max([numeric_only, min_count, ...]) |
计算组值的最大值。 |
SeriesGroupBy.mean([numeric_only, engine, ...]) |
计算组的平均值,不包括缺失值。 |
SeriesGroupBy.median([numeric_only]) |
计算组的中位数,不包括缺失值。 |
SeriesGroupBy.min([numeric_only, min_count, ...]) |
计算组值的最小值。 |
SeriesGroupBy.ngroup([ascending]) |
将每个组从 0 编号到组数 - 1。 |
SeriesGroupBy.nlargest([n, keep]) |
返回最大的 n 个元素。 |
SeriesGroupBy.nsmallest([n, keep]) |
返回最小的 n 个元素。 |
SeriesGroupBy.nth |
如果 n 是整数,则从每个组中取第 n 行,否则取行的子集。 |
SeriesGroupBy.nunique([dropna]) |
返回组中唯一元素的数量。 |
SeriesGroupBy.unique() |
返回每个组的唯一值。 |
SeriesGroupBy.ohlc() |
计算组的开盘价、最高价、最低价和收盘价,不包括缺失值。 |
SeriesGroupBy.pct_change([periods, ...]) |
计算每个值相对于组中前一个条目的百分比变化。 |
SeriesGroupBy.prod([numeric_only, min_count]) |
计算组值的乘积。 |
SeriesGroupBy.quantile([q, interpolation, ...]) |
返回给定分位数处的组值,类似于 numpy.percentile。 |
SeriesGroupBy.rank([method, ascending, ...]) |
在每个组内提供值的排名。 |
SeriesGroupBy.resample(rule, *args[, ...]) |
在使用 TimeGrouper 时提供重新采样。 |
SeriesGroupBy.rolling(*args, **kwargs) |
返回一个滚动分组器,为每个组提供滚动功能。 |
SeriesGroupBy.sample([n, frac, replace, ...]) |
返回每个组的随机样本项目。 |
SeriesGroupBy.sem([ddof, numeric_only]) |
计算组的均值标准误差,不包括缺失值。 |
SeriesGroupBy.shift([periods, freq, axis, ...]) |
将每个组的观察值移动若干周期。 |
SeriesGroupBy.size() |
计算组大小。 |
SeriesGroupBy.skew([axis, skipna, numeric_only]) |
返回组内无偏斜。 |
SeriesGroupBy.std([ddof, engine, ...]) |
计算组的标准偏差,不包括缺失值。 |
SeriesGroupBy.sum([numeric_only, min_count, ...]) |
计算组值的总和。 |
SeriesGroupBy.var([ddof, engine, ...]) |
计算组的方差,不包括缺失值。 |
SeriesGroupBy.tail([n]) |
返回每个组的最后 n 行。 |
SeriesGroupBy.take(indices[, axis]) |
返回每个组中给定 位置 索引中的元素。 |
SeriesGroupBy.value_counts([normalize, ...]) |
绘图和可视化
DataFrameGroupBy.boxplot([subplots, column, ...]) |
从 DataFrameGroupBy 数据制作箱线图。 |
|---|---|
DataFrameGroupBy.hist([column, by, grid, ...]) |
绘制 DataFrame 的列的直方图。 |
SeriesGroupBy.hist([by, ax, grid, ...]) |
使用 LIMITED 绘制输入系列的直方图。 |
DataFrameGroupBy.plot |
绘制 Series 或 DataFrame 的图表。 |
SeriesGroupBy.plot |
绘制 Series 或 DataFrame 的图表。 |
pandas.core.groupby.DataFrameGroupBy.__iter__
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.__iter__.html
DataFrameGroupBy.__iter__()
分组迭代器。
返回:
生成器产生 (name, 子集对象) 序列。
对于每个分组
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> for x, y in ser.groupby(level=0):
... print(f'{x}\n{y}\n')
a
a 1
a 2
dtype: int64
b
b 3
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> for x, y in df.groupby(by=["a"]):
... print(f'{x}\n{y}\n')
(1,)
a b c
0 1 2 3
1 1 5 6
(7,)
a b c
2 7 8 9
对于 Resampler:
>>> 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
>>> for x, y in ser.resample('MS'):
... print(f'{x}\n{y}\n')
2023-01-01 00:00:00
2023-01-01 1
2023-01-15 2
dtype: int64
2023-02-01 00:00:00
2023-02-01 3
2023-02-15 4
dtype: int64
pandas.core.groupby.SeriesGroupBy.\_\_iter\_\_
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.__iter__.html
SeriesGroupBy.__iter__()
分组迭代器。
返回值:
生成器产生 (名称, 子集对象) 序列
对于每个组
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> for x, y in ser.groupby(level=0):
... print(f'{x}\n{y}\n')
a
a 1
a 2
dtype: int64
b
b 3
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> for x, y in df.groupby(by=["a"]):
... print(f'{x}\n{y}\n')
(1,)
a b c
0 1 2 3
1 1 5 6
(7,)
a b c
2 7 8 9
对于 Resampler:
>>> 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
>>> for x, y in ser.resample('MS'):
... print(f'{x}\n{y}\n')
2023-01-01 00:00:00
2023-01-01 1
2023-01-15 2
dtype: int64
2023-02-01 00:00:00
2023-02-01 3
2023-02-15 4
dtype: int64
pandas.core.groupby.DataFrameGroupBy.groups
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.groups.html
property DataFrameGroupBy.groups
字典 {组名 -> 组标签}。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).groups
{'a': ['a', 'a'], 'b': ['b']}
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> df.groupby(by=["a"]).groups
{1: [0, 1], 7: [2]}
对于 Resampler:
>>> 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').groups
{Timestamp('2023-01-01 00:00:00'): 2, Timestamp('2023-02-01 00:00:00'): 4}
pandas.core.groupby.SeriesGroupBy.groups
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.groups.html
property SeriesGroupBy.groups
Dict {group name -> group labels}.
Examples
For SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).groups
{'a': ['a', 'a'], 'b': ['b']}
For DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> df.groupby(by=["a"]).groups
{1: [0, 1], 7: [2]}
For Resampler:
>>> 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').groups
{Timestamp('2023-01-01 00:00:00'): 2, Timestamp('2023-02-01 00:00:00'): 4}
pandas.core.groupby.DataFrameGroupBy.indices
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.indices.html
property DataFrameGroupBy.indices
字典 {分组名称 -> 分组索引}。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).indices
{'a': array([0, 1]), 'b': array([2])}
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).indices
{1: array([0, 1]), 7: array([2])}
对于 Resampler:
>>> 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').indices
defaultdict(<class 'list'>, {Timestamp('2023-01-01 00:00:00'): [0, 1],
Timestamp('2023-02-01 00:00:00'): [2, 3]})
pandas.core.groupby.SeriesGroupBy.indices
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.indices.html
property SeriesGroupBy.indices
字典 {组名 -> 组索引}。
示例
对于序列分组(SeriesGroupBy):
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).indices
{'a': array([0, 1]), 'b': array([2])}
对于数据帧分组(DataFrameGroupBy):
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).indices
{1: array([0, 1]), 7: array([2])}
对于重新采样器(Resampler):
>>> 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').indices
defaultdict(<class 'list'>, {Timestamp('2023-01-01 00:00:00'): [0, 1],
Timestamp('2023-02-01 00:00:00'): [2, 3]})
pandas.core.groupby.DataFrameGroupBy.get_group
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.get_group.html
DataFrameGroupBy.get_group(name, obj=None)
使用提供的名称构造组中的 DataFrame。
参数:
name对象
要作为 DataFrame 获取的组的名称。
objDataFrame,默认为 None
要从中获取 DataFrame 的 DataFrame。 如果为 None,则将使用调用 groupby 的对象。
自 2.1.0 版本起弃用:obj 已弃用,将在将来的版本中删除。 请改用df.iloc[gb.indices.get(name)]代替gb.get_group(name, obj=df)。
返回:
与 obj 相同类型
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).get_group("a")
a 1
a 2
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).get_group((1,))
a b c
owl 1 2 3
toucan 1 5 6
对于 Resampler:
>>> 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').get_group('2023-01-01')
2023-01-01 1
2023-01-15 2
dtype: int64
pandas.core.groupby.SeriesGroupBy.get_group
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.get_group.html
SeriesGroupBy.get_group(name, obj=None)
使用提供的名称从组构建 DataFrame。
参数:
name对象
要作为 DataFrame 获取的组的名称。
objDataFrame,默认为 None
从中获取 DataFrame 的 DataFrame。如果为 None,则将使用调用 groupby 的对象。
自版本 2.1.0 起已弃用:obj 已弃用,并将在将来的版本中删除。请改用 df.iloc[gb.indices.get(name)] 而不是 gb.get_group(name, obj=df)。
返回:
与 obj 相同类型
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).get_group("a")
a 1
a 2
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).get_group((1,))
a b c
owl 1 2 3
toucan 1 5 6
对于重新采样器:
>>> 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').get_group('2023-01-01')
2023-01-01 1
2023-01-15 2
dtype: int64
pandas.Grouper
class pandas.Grouper(*args, **kwargs)
Grouper 允许用户为对象指定分组指令。
此规范将通过 key 参数选择一列,或者如果给定了 level 和/或 axis 参数,则选择目标对象的索引级别。
如果将 axis 和/或 level 作为关键字传递给 Grouper 和 groupby,��Grouper 传递的值优先。
参数:
keystr,默认为 None
分组键,选择目标的分组列。
level名称/编号,默认为 None
目标索引的级别。
freqstr / 频率对象,默认为 None
如果目标选择(通过 key 或 level)是类似日期时间的对象,则将按指定频率进行分组。有关可用频率的完整规范,请参见这里。
axisstr、int,默认为 0
轴的编号/名称。
sortbool,默认为 False
是否对结果标签进行排序。
closed
区间的闭合端。仅当传递了 freq 参数时。
label
用于标记的区间边界。仅当传递了 freq 参数时。
convention
如果 grouper 是 PeriodIndex 并且传递了 freq 参数。
originTimestamp 或 str,默认为‘start_day’
要调整分组的时间戳。原点的时区必须与索引的时区匹配。如果是字符串,则必须是以下之一:
-
‘epoch’:原点为 1970-01-01
-
‘start’:原点为时间序列的第一个值
-
‘start_day’:原点为时间序列的第一天午夜
-
‘end’:原点为时间序列的最后一个值
-
‘end_day’:原点为最后一天的午夜
版本 1.3.0 中的新功能。
offsetTimedelta 或 str,默认为 None
添加到原点的偏移时间差。
dropnabool,默认为 True
如果为 True,并且组键包含 NA 值,则 NA 值与行/列一起被删除。如果为 False,NA 值也将被视为组中的键。
返回:
Grouper 或 pandas.api.typing.TimeGrouper
如果freq不是None,则返回一个 TimeGrouper。否则,返回一个 Grouper。
示例
df.groupby(pd.Grouper(key="Animal"))等同于df.groupby('Animal')
>>> df = pd.DataFrame(
... {
... "Animal": ["Falcon", "Parrot", "Falcon", "Falcon", "Parrot"],
... "Speed": [100, 5, 200, 300, 15],
... }
... )
>>> df
Animal Speed
0 Falcon 100
1 Parrot 5
2 Falcon 200
3 Falcon 300
4 Parrot 15
>>> df.groupby(pd.Grouper(key="Animal")).mean()
Speed
Animal
Falcon 200.0
Parrot 10.0
指定对列'Publish date'进行重新采样操作
>>> df = pd.DataFrame(
... {
... "Publish date": [
... pd.Timestamp("2000-01-02"),
... pd.Timestamp("2000-01-02"),
... pd.Timestamp("2000-01-09"),
... pd.Timestamp("2000-01-16")
... ],
... "ID": [0, 1, 2, 3],
... "Price": [10, 20, 30, 40]
... }
... )
>>> df
Publish date ID Price
0 2000-01-02 0 10
1 2000-01-02 1 20
2 2000-01-09 2 30
3 2000-01-16 3 40
>>> df.groupby(pd.Grouper(key="Publish date", freq="1W")).mean()
ID Price
Publish date
2000-01-02 0.5 15.0
2000-01-09 2.0 30.0
2000-01-16 3.0 40.0
如果要根据固定时间戳调整箱子的起始点:
>>> start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00'
>>> rng = pd.date_range(start, end, freq='7min')
>>> ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
>>> ts
2000-10-01 23:30:00 0
2000-10-01 23:37:00 3
2000-10-01 23:44:00 6
2000-10-01 23:51:00 9
2000-10-01 23:58:00 12
2000-10-02 00:05:00 15
2000-10-02 00:12:00 18
2000-10-02 00:19:00 21
2000-10-02 00:26:00 24
Freq: 7min, dtype: int64
>>> ts.groupby(pd.Grouper(freq='17min')).sum()
2000-10-01 23:14:00 0
2000-10-01 23:31:00 9
2000-10-01 23:48:00 21
2000-10-02 00:05:00 54
2000-10-02 00:22:00 24
Freq: 17min, dtype: int64
>>> ts.groupby(pd.Grouper(freq='17min', origin='epoch')).sum()
2000-10-01 23:18:00 0
2000-10-01 23:35:00 18
2000-10-01 23:52:00 27
2000-10-02 00:09:00 39
2000-10-02 00:26:00 24
Freq: 17min, dtype: int64
>>> ts.groupby(pd.Grouper(freq='17min', origin='2000-01-01')).sum()
2000-10-01 23:24:00 3
2000-10-01 23:41:00 15
2000-10-01 23:58:00 45
2000-10-02 00:15:00 45
Freq: 17min, dtype: int64
如果要根据偏移时间差调整箱子的起始点,则以下两行是等效的:
>>> ts.groupby(pd.Grouper(freq='17min', origin='start')).sum()
2000-10-01 23:30:00 9
2000-10-01 23:47:00 21
2000-10-02 00:04:00 54
2000-10-02 00:21:00 24
Freq: 17min, dtype: int64
>>> ts.groupby(pd.Grouper(freq='17min', offset='23h30min')).sum()
2000-10-01 23:30:00 9
2000-10-01 23:47:00 21
2000-10-02 00:04:00 54
2000-10-02 00:21:00 24
Freq: 17min, dtype: int64
要替换已弃用的 base 参数的使用,现在可以使用 offset,在此示例中,等效于 base=2:
>>> ts.groupby(pd.Grouper(freq='17min', offset='2min')).sum()
2000-10-01 23:16:00 0
2000-10-01 23:33:00 9
2000-10-01 23:50:00 36
2000-10-02 00:07:00 39
2000-10-02 00:24:00 24
Freq: 17min, dtype: int64
pandas.NamedAgg
原文:
pandas.pydata.org/docs/reference/api/pandas.NamedAgg.html
class pandas.NamedAgg(column, aggfunc)
控制输出列名称的列特定聚合的辅助函数。
typing.NamedTuple 的子类。
参数:
column 可散列
DataFrame 中应用 aggfunc 的列标签。
aggfunc 函数或字符串
应用于提供列的函数。如果是字符串,则是内置 pandas 函数的名称。
示例
>>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], 1: [10, 11, 12]})
>>> agg_a = pd.NamedAgg(column="a", aggfunc="min")
>>> agg_1 = pd.NamedAgg(column=1, aggfunc=lambda x: np.mean(x))
>>> df.groupby("key").agg(result_a=agg_a, result_1=agg_1)
result_a result_1
key
1 -1 10.5
2 1 12.0
属性
aggfunc |
字段编号 1 的别名 |
|---|---|
column |
字段编号 0 的别名 |
方法
count(value, /) |
返回值出现的次数。 |
|---|---|
index(value[, start, stop]) |
返回值的第一个索引。 |
pandas.core.groupby.SeriesGroupBy.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.apply.html
SeriesGroupBy.apply(func, *args, **kwargs)
将函数func按组应用,并将结果组合在一起。
传递给apply的函数必须将 Series 作为其第一个参数,并返回 DataFrame、Series 或标量。然后,apply将负责将结果组合成单个 DataFrame 或 Series。因此,apply是一种非常灵活的分组方法。
虽然apply是一个非常灵活的方法,但它的缺点是使用它可能比使用更具体的方法(如agg或transform)要慢得多。Pandas 提供了许多方法,这些方法对于特定目的而言要比使用apply快得多,因此在使用apply之前请尝试使用它们。
参数:
funccallable
一个可调用对象,以其第一个参数为 Series,并返回一个 dataframe、一个 series 或一个标量。此外,可调用对象可能会接受位置参数和关键字参数。
include_groupsbool,默认为 True
当为 True 时,将尝试将func应用于 DataFrame 的分组,如果这引发了 TypeError,则在计算结果时将排除分组。当为 False 时,在应用func时将排除分组。
版本 2.2.0 中的新功能。
自版本 2.2.0 起弃用:将include_groups设置为 True 已弃用。在将来的 pandas 版本中,只允许值为 False。
args, kwargstuple 和 dict
传递给func的可选位置和关键字参数。
返回:
Series 或 DataFrame
另请参阅
pipe
将函数应用于完整的 GroupBy 对象,而不是应用于每个组。
aggregate
将聚合函数应用于 GroupBy 对象。
transform
将函数逐列应用于 GroupBy 对象。
Series.apply
将函数应用于 Series。
DataFrame.apply
将函数应用于 DataFrame 的每一行或每一列。
注意事项
在 1.3.0 版本中更改:结果的数据类型将反映传递的func的返回值,请参阅下面的示例。
变异传递的函数可能会产生意外的行为或错误,并且不受支持。有关更多详细信息,请参阅 使用用户定义的函数 (UDF) 方法进行变异。
示例
>>> s = pd.Series([0, 1, 2], index='a a b'.split())
>>> g1 = s.groupby(s.index, group_keys=False)
>>> g2 = s.groupby(s.index, group_keys=True)
从上面的 s 我们可以看到 g 有两个组,a 和 b。注意 g1 和 g2 有两个组,a 和 b,只是它们的 group_keys 参数不同。以不同的方式调用 apply,我们可以获得不同的分组结果:
Example 1: 传递给 apply 的函数以 Series 作为其参数并返回一个 Series。apply 将每个组的结果合并到一个新的 Series 中。
在 1.3.0 版本中更改:结果的数据类型将反映传递的 func 的返回值。
>>> g1.apply(lambda x: x * 2 if x.name == 'a' else x / 2)
a 0.0
a 2.0
b 1.0
dtype: float64
在上面的例子中,组不是索引的一部分。我们可以通过使用 g2 并设置 group_keys=True 来包含它们:
>>> g2.apply(lambda x: x * 2 if x.name == 'a' else x / 2)
a a 0.0
a 2.0
b b 1.0
dtype: float64
Example 2: 传递给 apply 的函数以 Series 作为其参数并返回一个标量。apply 将每个组的结果合并到一个 Series 中,包括适当地设置索引:
>>> g1.apply(lambda x: x.max() - x.min())
a 1
b 0
dtype: int64
这里的 group_keys 参数没有影响,因为结果与输入不是类似索引的(即 一个 transform)。
>>> g2.apply(lambda x: x.max() - x.min())
a 1
b 0
dtype: int64
pandas.core.groupby.DataFrameGroupBy.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.apply.html
DataFrameGroupBy.apply(func, *args, include_groups=True, **kwargs)
将函数func逐组应用并将结果组合在一起。
传递给apply的函数必须将一个 DataFrame 作为其第一个参数,并返回一个 DataFrame、Series 或标量。然后,apply将负责将结果组合回一个单一的 DataFrame 或 Series。因此,apply是一种非常灵活的分组方法。
虽然apply是一种非常灵活的方法,但它的缺点是使用它可能会比使用更具体的方法(如agg或transform)要慢得多。Pandas 提供了一系列方法,用于特定目的比使用apply要快得多,因此在使用apply之前,请尝试使用它们。
参数:
func可调用对象
一个以 DataFrame 作为其第一个参数的可调用对象,并返回一个 DataFrame、Series 或标量。此外,可调用对象还可以接受位置和关键字参数。
include_groups布尔值,默认为 True
当为 True 时,将尝试将func应用于 DataFrame 的列作为分组的情况。如果这引发了 TypeError,则结果将排除在外。当为 False 时,应用func时将排除分组。
自版本 2.2.0 开始。
自版本 2.2.0 起弃用:设置 include_groups 为 True 已弃用。在将来的 pandas 版本中,只允许值为 False。
args, kwargs元组和字典
传递给func的可选位置和关键字参数。
返回:
Series 或 DataFrame
另请参见
pipe
将函数应用于完整的 GroupBy 对象,而不是每个组。
aggregate
将聚合函数应用于 GroupBy 对象。
transform
将函数逐列应用于 GroupBy 对象。
Series.apply
对 Series 应用函数。
DataFrame.apply
对 DataFrame 的每一行或每一列应用函数。
注意事项
从版本 1.3.0 开始更改:结果的 dtype 将反映传递的func的返回值,请参见下面的示例。
对传递的对象进行变异的函数可能会产生意外的行为或错误,并且不受支持。有关详细信息,请参阅使用用户定义函数 (UDF) 进行变异。
示例
>>> df = pd.DataFrame({'A': 'a a b'.split(),
... 'B': [1, 2, 3],
... 'C': [4, 6, 5]})
>>> g1 = df.groupby('A', group_keys=False)
>>> g2 = df.groupby('A', group_keys=True)
注意,g1和g2有两个组,a和b,并且只在它们的group_keys参数上有所不同。以各种方式调用 apply,我们可以得到不同的分组结果:
示例 1:下面传递给 apply 的函数以 DataFrame 作为其参数,并返回一个 DataFrame。apply 将每个组的结果合并为一个新的 DataFrame:
>>> g1[['B', 'C']].apply(lambda x: x / x.sum())
B C
0 0.333333 0.4
1 0.666667 0.6
2 1.000000 1.0
在上述情况下,组不是索引的一部分。我们可以通过使用g2,其中group_keys=True来包含它们:
>>> g2[['B', 'C']].apply(lambda x: x / x.sum())
B C
A
a 0 0.333333 0.4
1 0.666667 0.6
b 2 1.000000 1.0
示例 2:传递给 apply 的函数以 DataFrame 作为其参数,并返回一个 Series。apply 将每个组的结果合并为一个新的 DataFrame。
1.3.0 版本更改:结果的 dtype 将反映传递的func的返回值。
>>> g1[['B', 'C']].apply(lambda x: x.astype(float).max() - x.min())
B C
A
a 1.0 2.0
b 0.0 0.0
>>> g2[['B', 'C']].apply(lambda x: x.astype(float).max() - x.min())
B C
A
a 1.0 2.0
b 0.0 0.0
在这里,group_keys参数没有影响,因为结果与输入不是相似索引(即 a transform)。
示例 3:传递给 apply 的函数以 DataFrame 作为其参数,并返回标量。apply 将每个组的结果合并为一个 Series,包括适当设置索引:
>>> g1.apply(lambda x: x.C.max() - x.B.min(), include_groups=False)
A
a 5
b 2
dtype: int64
pandas.core.groupby.SeriesGroupBy.agg
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.agg.html
SeriesGroupBy.agg(func=None, *args, engine=None, engine_kwargs=None, **kwargs)
使用一个或多个操作在指定轴上进行聚合。
参数:
func函数、str、list、dict 或 None
用于聚合数据的函数。如果是函数,则必须在传递 Series 或传递给 Series.apply 时起作用。
接受的组合有:
-
函数
-
字符串函数名称
-
函数列表和/或函数名称,例如
[np.sum, 'mean'] -
无,此时将使用
**kwargs与命名聚合。这里的输出每个元素都有一列**kwargs。列的名称是关键字,而值确定用于计算列中值的聚合。也可以接受指定
engine='numba'的 Numba JIT 函数。此引擎仅支持传递单个函数。如果选择了
'numba'引擎,则函数必须是一个用户定义的函数,函数签名中的第一个和第二个参数分别为values和index。每个组的索引将传递给用户定义的函数,并可选择用于使用。
自版本 2.1.0 起弃用:传递字典已弃用,并将在未来的 pandas 版本中引发错误。请传递聚合列表。
*args
传递给 func 的位置参数。
enginestr,默认为 None
-
'cython':通过 cython 的 C 扩展运行函数。 -
'numba':通过 numba 的 JIT 编译代码运行函数。 -
None:默认为'cython'或全局设置compute.use_numba
engine_kwargsdict,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs是{'nopython': True, 'nogil': False, 'parallel': False},将应用于函数
**kwargs
-
如果
func为 None,则使用**kwargs来定义输出名称和聚合方式,通过命名聚合查看func条目。 -
否则,要传递给 func 的关键字参数。
返回:
系列
另请参见
Series.groupby.apply
对每个组应用函数 func,并将结果组合在一起。
Series.groupby.transform
根据给定函数在每个组上转换 Series。
Series.aggregate
使用一个或多个操作在指定轴上进行聚合。
注意事项
使用engine='numba'时,内部不会有“回退”行为。组数据和组索引将作为 numpy 数组传递给 JIT 用户定义的函数,不会尝试任何替代执行。
对传递对象进行突变的函数可能会产生意外行为或错误,并且不受支持。有关更多详情,请参阅使用用户定义函数 (UDF) 方法进行突变。
自 1.3.0 版更改:结果 dtype 将反映传递的func的返回值,请参见下面的示例。
示例
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.groupby([1, 1, 2, 2]).min()
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg('min')
1 1
2 3
dtype: int64
>>> s.groupby([1, 1, 2, 2]).agg(['min', 'max'])
min max
1 1 2
2 3 4
可以通过传递所需的列名和聚合方式作为关键字参数来控制输出列名。
>>> s.groupby([1, 1, 2, 2]).agg(
... minimum='min',
... maximum='max',
... )
minimum maximum
1 1 2
2 3 4
自 1.3.0 版更改:结果 dtype 将反映聚合函数的返回值。
>>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min())
1 1.0
2 3.0
dtype: float64
pandas.core.groupby.DataFrameGroupBy.agg
原文:
pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.agg.html
DataFrameGroupBy.agg(func=None, *args, engine=None, engine_kwargs=None, **kwargs)
使用一个或多个操作在指定轴上进行聚合。
参数:
func函数、字符串、列表、字典或 None
用于聚合数据的函数。如果是函数,则必须能够在传递给 DataFrame 或传递给 DataFrame.apply 时起作用。
接受的组合为:
-
函数
-
字符串函数名
-
函数列表和/或函数名称,例如
[np.sum, 'mean'] -
轴标签->函数、函数名称或这些的列表的字典。
-
None,此时将使用
**kwargs与命名聚合一起使用。这里输出的每一列都有一个关键字作为列名,而值确定用于计算列中值的聚合。还可以接受具有指定
engine='numba'的 Numba JIT 函数。此引擎仅支持传递单个函数。如果选择
'numba'引擎,则函数必须是具有函数签名中的第一个和第二个参数作为values和index的用户定义函数。每个组的索引将传递给用户定义的函数,并可选择用于使用。
*args
传递给 func 的位置参数。
engine字符串,默认为 None
-
'cython':通过 cython 的 C 扩展运行函数。 -
'numba':通过 numba 的 JIT 编译代码运行函数。 -
None:默认为'cython'或全局设置compute.use_numba
engine_kwargs字典,默认为 None
-
对于
'cython'引擎,不接受engine_kwargs -
对于
'numba'引擎,引擎可以接受nopython、nogil和parallel字典键。值必须是True或False。'numba'引擎的默认engine_kwargs为{'nopython': True, 'nogil': False, 'parallel': False},将应用于函数
**kwargs
-
如果
func为 None,则使用**kwargs通过命名聚合来定义输出名称和聚合。请参阅func条目。 -
否则,要传递到 func 中的关键字参数。
返回:
DataFrame
另请参阅
DataFrame.groupby.apply
对组应用函数 func,并将结果组合在一起。
DataFrame.groupby.transform
根据给定函数在每个组上转换 Series。
DataFrame.aggregate
使用一个或多个操作在指定轴上进行聚合。
注释
使用engine='numba'时,内部不会有“回退”行为。组数据和组索引将作为 numpy 数组传递给 JIT 化的用户定义函数,并且不会尝试其他执行尝试。
改变传递对象的函数可能会产生意外行为或错误,并且不受支持。有关更多详情,请参阅使用用户定义函数(UDF)方法进行变异。
在版本 1.3.0 中更改:结果的数据类型将反映传递的func的返回值,请参见下面的示例。
示例
>>> data = {"A": [1, 1, 2, 2],
... "B": [1, 2, 3, 4],
... "C": [0.362838, 0.227877, 1.267767, -0.562860]}
>>> df = pd.DataFrame(data)
>>> df
A B C
0 1 1 0.362838
1 1 2 0.227877
2 2 3 1.267767
3 2 4 -0.562860
聚合是针对每列的。
>>> df.groupby('A').agg('min')
B C
A
1 1 0.227877
2 3 -0.562860
多重聚合
>>> df.groupby('A').agg(['min', 'max'])
B C
min max min max
A
1 1 2 0.227877 0.362838
2 3 4 -0.562860 1.267767
选择一个列进行聚合
>>> df.groupby('A').B.agg(['min', 'max'])
min max
A
1 1 2
2 3 4
用于聚合的用户定义函数
>>> df.groupby('A').agg(lambda x: sum(x) + 2)
B C
A
1 5 2.590715
2 9 2.704907
每列不同的聚合
>>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'})
B C
min max sum
A
1 1 2 0.590715
2 3 4 0.704907
要使用不同的聚合控制每列的输出名称,pandas 支持“命名聚合”。
>>> df.groupby("A").agg(
... b_min=pd.NamedAgg(column="B", aggfunc="min"),
... c_sum=pd.NamedAgg(column="C", aggfunc="sum")
... )
b_min c_sum
A
1 1 0.590715
2 3 0.704907
-
关键词是输出列名
-
这些值是元组,第一个元素是要选择的列,第二个元素是要应用于该列的聚合。Pandas 提供了
pandas.NamedAgg命名元组,其字段为['column', 'aggfunc'],以使参数更清晰。像往常一样,聚合可以是可调用的或字符串别名。
更多请参阅命名聚合。
在版本 1.3.0 中更改:结果的数据类型将反映聚合函数的返回值。
>>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min())
B
A
1 1.0
2 3.0


浙公网安备 33010602011771号