系列#
本页面提供了所有公共Series方法的概述。
- class polars.Series(
- name: str | ArrayLike | None = None,
- values: ArrayLike | None = None,
- dtype: PolarsDataType | None = None,
- *,
- strict: bool = True,
- nan_to_null: bool = False,
Series 表示 polars DataFrame 中的单个列。
- Parameters:
- namestr, default None
系列的名称。在DataFrame中使用时,将用作列名。 如果未指定,名称将设置为空字符串。
- valuesArrayLike, default None
一维数据以各种形式存在。支持的有:序列、系列、pyarrow数组和numpy ndarray。
- dtypeDataType, default None
结果Series的数据类型。如果设置为
None(默认),则数据类型从values输入中推断。数据类型推断的策略取决于strict参数:如果
strict设置为 True(默认值),推断的数据类型等于第一个非空值,如果所有值都为空,则为Null。如果
strict设置为 False,推断出的数据类型是值的超类型,如果找不到超类型,则为Object。警告:需要完整遍历所有值以确定超类型。如果没有传递任何值,结果数据类型是
Null。
- strictbool, default True
如果任何值与给定或推断的数据类型不完全匹配,则抛出错误。如果设置为
False,则与数据类型不匹配的值将被强制转换为该数据类型,或者如果无法转换,则设置为null。- nan_to_nullbool, default False
如果使用numpy数组创建此Series,请指明如何处理np.nan值。(此参数对非numpy数据无效)。
示例
通过按位置指定名称和值来构建Series:
>>> s = pl.Series("a", [1, 2, 3]) >>> s shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
请注意,dtype 自动推断为 polars Int64:
>>> s.dtype Int64
使用特定的dtype构造一个Series:
>>> s2 = pl.Series("a", [1, 2, 3], dtype=pl.Float32) >>> s2 shape: (3,) Series: 'a' [f32] [ 1.0 2.0 3.0 ]
可以使用值作为第一个位置参数来构造一个Series。 这种语法被认为是一种反模式,但在某些情况下可能有用。 您必须通过关键字指定任何其他参数。
>>> s3 = pl.Series([1, 2, 3]) >>> s3 shape: (3,) Series: '' [i64] [ 1 2 3 ]
方法:
计算绝对值。
重命名系列。
返回列中的所有值是否都为
True。返回列中的任何值是否为
True。将一个Series附加到这个Series上。
唯一值的近似计数。
计算元素级的反余弦值。
计算元素级的反双曲余弦值。
计算元素级的反正弦值。
计算元素级的反双曲正弦值。
计算元素级的反正切值。
计算元素级的反双曲正切值。
获取最大值的索引。
获取最小值的索引。
获取将对此系列进行排序的索引值。
获取布尔系列评估为True的索引值。
获取唯一索引作为Series。
执行按位与的聚合操作。
评估设置的位数。
评估未设置的Self数量。
评估在遇到未设置的位之前的最重要的设置位数。
评估在遇到设置位之前最高有效未设置位的数量。
执行按位或的聚合操作。
评估在遇到未设置的位之前的最不重要的设置位数。
评估在遇到设置位之前的最不重要的未设置位的数量。
执行按位异或的聚合操作。
返回
k个最小的元素。在数据类型之间进行转换。
计算元素的立方根。
向上取整到最接近的整数值。
获取每个单独块的长度。
创建一个当前Series的空副本,包含零到'n'个元素。
将给定边界之外的值设置为边界值。
创建此系列的副本。
计算元素级别的余弦值。
计算双曲余弦的逐元素值。
计算元素级的余切值。
返回列中非空元素的数量。
返回列中非空值的累计计数。
获取一个数组,其中包含在每个元素处计算的累积最大值。
获取一个数组,其中包含在每个元素处计算的累积最小值。
获取一个数组,其中包含在每个元素处计算的累积乘积。
获取一个数组,其中每个元素都计算了累积和。
在每次迭代增加
1个槽的滑动窗口上运行表达式。将连续值分箱为离散类别。
系列的快速摘要统计。
计算偏移项之间的第一个离散差异。
计算两个Series之间的点积/内积。
删除所有浮点数的NaN值。
删除所有空值。
计算熵。
方法等同于操作符表达式
series == other。等同于相等运算符
series == other的方法,其中None == None。检查Series是否等于另一个Series。
返回Series的总(堆)分配大小的估计值。
计算指数加权移动平均。
计算基于时间的指数加权移动平均。
计算指数加权移动标准差。
计算指数加权移动方差。
计算指数,逐元素。
展开一个列表系列。
使用另一个Series的值扩展此Series支持的内存。
用于使用值的'n'个副本扩展Series的极快方法。
用填充值填充浮点数的NaN值。
使用指定的值或策略填充空值。
通过布尔掩码过滤元素。
获取Series的第一个元素。
向下舍入到最接近的整数值。
按索引取值。
取Series中的每第n个值并返回为新的Series。
方法等同于操作符表达式
series >= other。获取此Series的块作为Series列表。
方法等同于操作符表达式
series > other。检查Series是否包含一个或多个空值。
检查Series是否包含一个或多个空值。
哈希系列。
获取前
n个元素。将值分入桶中并计算它们的出现次数。
将值聚合到一个列表中。
使用插值填充空值。
使用基于另一列的插值来填充空值。
获取一个布尔掩码,表示值是否在给定的下限/上限之间。
获取所有重复值的掩码。
检查Series是否为空。
返回一个布尔系列,指示哪些值是有限的。
返回一个布尔掩码,指示每个不同值的首次出现。
检查此系列中的元素是否在另一个系列中。
返回一个布尔系列,指示哪些值是无限的。
返回一个布尔掩码,指示每个不同值的最后一次出现。
返回一个布尔系列,指示哪些值是NaN。
返回一个布尔系列,指示哪些值不是NaN。
返回一个布尔系列,指示哪些值不为空。
返回一个布尔系列,指示哪些值为空。
检查Series是否已排序。
获取所有唯一值的掩码。
将Series作为标量返回,或返回给定索引处的元素。
计算数据集的峰度(Fisher 或 Pearson)。
获取Series的最后一个元素。
方法等同于操作符表达式
series <= other。返回Series中的元素数量。
获取前
n个元素。计算给定底数的对数。
计算输入数组的以10为底的对数,逐元素进行。
计算输入数组加一的自然对数,逐元素进行。
返回此Series数据类型的下限作为一个单位Series。
方法等同于操作符表达式
series < other。在此系列的元素上映射自定义/用户定义的函数(UDF)。
获取此系列中的最大值。
将此系列减少到平均值。
获取此系列的中位数。
获取此系列中的最小值。
计算出现频率最高的值。
获取此系列包含的块数。
计算此系列中唯一值的数量。
获取最大值,但传播/污染遇到的NaN值。
获取最小值,但传播/污染遇到的NaN值。
方法等同于操作符表达式
series != other。等价于相等运算符
series != other的方法,其中None == None。创建一个新的Series,并用给定索引的值填充。
对布尔系列进行取反。
计算此系列中的空值数量。
计算值之间的百分比变化。
获取局部最大峰的布尔掩码。
获取局部最小峰的布尔掩码。
将给定的指数提升到幂。
将此系列减少为乘积值。
将连续值根据其分位数分箱到离散类别中。
获取此系列的分位数值。
为数据分配排名,适当处理并列情况。
为这个系列创建一个单一的内存块。
将底层位重新解释为有符号/无符号整数。
重命名此系列。
用相同数据类型的其他值替换值。
用不同的值替换所有值。
将此系列重塑为扁平系列或数组系列。
返回反向排序的Series。
使用游程编码压缩Series数据。
为每次运行的相同值获取一个唯一的整数ID。
计算自定义滚动窗口函数。
对此数组中的值应用滚动最大值(移动最大值)。
对此数组中的值应用滚动平均值(移动平均值)。
计算滚动中位数。
对此数组中的值应用滚动最小值(移动最小值)。
计算滚动分位数。
计算滚动偏度。
计算滚动标准差。
对此数组中的值应用滚动求和(移动求和)。
计算滚动方差。
将底层浮点数据四舍五入到
decimals位小数。四舍五入到指定的有效数字位数。
从这个系列中取样。
在索引位置设置值。
找到应插入元素以保持顺序的索引。
设置掩码值。
将Series标记为“已排序”。
将值按给定的索引数进行移动。
将数值列缩小到所需的最小数据类型。
缩小系列内存使用。
打乱此系列的内容。
计算数值类型的逐元素符号函数。
计算元素的正弦值。
计算双曲正弦的逐元素值。
计算数据集的样本偏度。
获取此系列的一个切片。
对这个系列进行排序。
计算元素的平方根。
获取此系列的标准差。
将此系列减少为总和值。
获取最后
n个元素。计算元素的正切值。
计算双曲正切的逐元素值。
返回底层的Arrow数组。
获取虚拟/指示变量。
将此系列转换为DataFrame。
将系列转换为可实例化的字符串表示。
将此系列转换为Jax数组。
将此系列转换为Python列表。
将此系列转换为NumPy ndarray。
将此系列转换为pandas系列。
将逻辑数据类型转换为物理表示。
将此系列转换为PyTorch张量。
返回
k个最大的元素。获取系列中的唯一元素。
返回按出现顺序排列的唯一值的计数。
返回此Series数据类型的上限作为一个单位Series。
计算唯一值的出现次数。
获取此系列数据的方差。
根据给定的掩码从自身或其他中取值。
属性:
- abs() Series[source]
计算绝对值。
与
abs(series)相同。示例
>>> s = pl.Series([1, -2, -3]) >>> s.abs() shape: (3,) Series: '' [i64] [ 1 2 3 ]
- alias(name: str) Series[source]
重命名系列。
- Parameters:
- name
新名称。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.alias("b") shape: (3,) Series: 'b' [i64] [ 1 2 3 ]
- all(*, ignore_nulls: bool = True) bool | None[source]
返回列中的所有值是否都为
True。仅适用于数据类型为
Boolean的列。- Parameters:
- ignore_nulls
忽略空值(默认)。
如果设置为
False,则使用Kleene逻辑来处理空值: 如果列包含任何空值且没有False值, 则输出为None。
- Returns:
- bool or None
示例
>>> pl.Series([True, True]).all() True >>> pl.Series([False, True]).all() False >>> pl.Series([None, True]).all() True
通过设置
ignore_nulls=False来启用Kleene逻辑。>>> pl.Series([None, True]).all(ignore_nulls=False) # Returns None
- any(*, ignore_nulls: bool = True) bool | None[source]
返回列中的任何值是否为
True。仅适用于数据类型为
Boolean的列。- Parameters:
- ignore_nulls
忽略空值(默认)。
如果设置为
False,则使用Kleene逻辑来处理空值: 如果列包含任何空值且没有True值, 则输出为None。
- Returns:
- bool or None
示例
>>> pl.Series([True, False]).any() True >>> pl.Series([False, False]).any() False >>> pl.Series([None, False]).any() False
通过设置
ignore_nulls=False来启用Kleene逻辑。>>> pl.Series([None, False]).any(ignore_nulls=False) # Returns None
- append(other: Series) Self[source]
将一个Series附加到这个Series上。
结果系列将由多个块组成。
- Parameters:
- other
要附加的系列。
警告
此方法会就地修改序列。返回序列仅为了方便。
另请参阅
示例
>>> a = pl.Series("a", [1, 2, 3]) >>> b = pl.Series("b", [4, 5]) >>> a.append(b) shape: (5,) Series: 'a' [i64] [ 1 2 3 4 5 ]
结果系列将由多个块组成。
>>> a.n_chunks() 2
- arccos() Series[source]
计算元素级的反余弦值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.arccos() shape: (3,) Series: 'a' [f64] [ 0.0 1.570796 3.141593 ]
- arccosh() Series[source]
计算元素级的反双曲余弦值。
示例
>>> s = pl.Series("a", [5.0, 1.0, 0.0, -1.0]) >>> s.arccosh() shape: (4,) Series: 'a' [f64] [ 2.292432 0.0 NaN NaN ]
- arcsin() Series[source]
计算元素级的反正弦值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.arcsin() shape: (3,) Series: 'a' [f64] [ 1.570796 0.0 -1.570796 ]
- arcsinh() Series[source]
计算元素级的反双曲正弦值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.arcsinh() shape: (3,) Series: 'a' [f64] [ 0.881374 0.0 -0.881374 ]
- arctan() Series[source]
计算元素级的反正切值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.arctan() shape: (3,) Series: 'a' [f64] [ 0.785398 0.0 -0.785398 ]
- arctanh() Series[source]
计算元素级的反双曲正切值。
示例
>>> s = pl.Series("a", [2.0, 1.0, 0.5, 0.0, -0.5, -1.0, -1.1]) >>> s.arctanh() shape: (7,) Series: 'a' [f64] [ NaN inf 0.549306 0.0 -0.549306 -inf NaN ]
- arg_max() int | None[source]
获取最大值的索引。
- Returns:
- int
示例
>>> s = pl.Series("a", [3, 2, 1]) >>> s.arg_max() 0
- arg_min() int | None[source]
获取最小值的索引。
- Returns:
- int
示例
>>> s = pl.Series("a", [3, 2, 1]) >>> s.arg_min() 2
- arg_sort( ) Series[source]
获取将对此系列进行排序的索引值。
- Parameters:
- descending
按降序排序。
- nulls_last
将空值放在最后而不是最前面。
另请参阅
Series.gather按索引取值。
Series.rank获取每行的排名。
示例
>>> s = pl.Series("a", [5, 3, 4, 1, 2]) >>> s.arg_sort() shape: (5,) Series: 'a' [u32] [ 3 4 1 2 0 ]
- arg_true() Series[source]
获取布尔系列评估为True的索引值。
- Returns:
- Series
数据类型为
UInt32的系列。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> (s == 2).arg_true() shape: (1,) Series: 'a' [u32] [ 1 ]
- arg_unique() Series[source]
获取唯一索引作为Series。
- Returns:
- Series
示例
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.arg_unique() shape: (3,) Series: 'a' [u32] [ 0 1 3 ]
- bitwise_count_ones() Self[source]
评估设置的位数。
- bitwise_count_zeros() Self[source]
评估未设置的Self数量。
- bitwise_leading_ones() Self[source]
评估在遇到未设置的位之前的最重要的设置位数。
- bitwise_leading_zeros() Self[source]
评估在遇到设置位之前最高有效未设置位的数量。
- bitwise_trailing_ones() Self[source]
评估在遇到未设置的位之前的最不重要的设置位数。
- bitwise_trailing_zeros() Self[source]
评估在遇到设置位之前的最不重要的未设置位的数量。
- bottom_k(k: int = 5) Series[source]
返回
k个最小的元素。非空元素总是优先于空元素。输出不保证按任何特定顺序排列,如果您希望输出排序,请在此函数后调用
sort()。这具有时间复杂度:
\[O(n)\]- Parameters:
- k
返回的元素数量。
另请参阅
示例
>>> s = pl.Series("a", [2, 5, 1, 4, 3]) >>> s.bottom_k(3) shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
- cast(
- dtype: type[int | float | str | bool] | PolarsDataType,
- *,
- strict: bool = True,
- wrap_numerical: bool = False,
在数据类型之间进行转换。
- Parameters:
- dtype
要转换到的数据类型。
- strict
如果为True,无效的转换将生成异常而不是
null。- wrap_numerical
如果为True,数值转换将包裹溢出值,而不是将转换标记为无效。
示例
>>> s = pl.Series("a", [True, False, True]) >>> s shape: (3,) Series: 'a' [bool] [ true false true ]
>>> s.cast(pl.UInt32) shape: (3,) Series: 'a' [u32] [ 1 0 1 ]
- cbrt() Series[source]
计算元素的立方根。
优化为
>>> pl.Series([1, 2]) ** (1.0 / 3) shape: (2,) Series: '' [f64] [ 1.0 1.259921 ]
示例
>>> s = pl.Series([1, 2, 3]) >>> s.cbrt() shape: (3,) Series: '' [f64] [ 1.0 1.259921 1.44225 ]
- ceil() Series[source]
向上取整到最接近的整数值。
仅适用于浮点型Series。
示例
>>> s = pl.Series("a", [1.12345, 2.56789, 3.901234]) >>> s.ceil() shape: (3,) Series: 'a' [f64] [ 2.0 3.0 4.0 ]
- chunk_lengths() list[int][source]
获取每个单独块的长度。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s2 = pl.Series("a", [4, 5, 6])
串联Series,设置rechunk = True
>>> pl.concat([s, s2], rechunk=True).chunk_lengths() [6]
串联Series,rechunk = False
>>> pl.concat([s, s2], rechunk=False).chunk_lengths() [3, 3]
- clear(n: int = 0) Series[source]
创建一个当前Series的空副本,包含零到'n'个元素。
副本具有相同的名称/数据类型,但没有数据。
- Parameters:
- n
返回清除后的帧中的(空)元素数量。
另请参阅
clone便宜的深拷贝/克隆。
示例
>>> s = pl.Series("a", [None, True, False]) >>> s.clear() shape: (0,) Series: 'a' [bool] [ ]
>>> s.clear(n=2) shape: (2,) Series: 'a' [bool] [ null null ]
- clip(
- lower_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
- upper_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None,
将给定边界之外的值设置为边界值。
- Parameters:
- lower_bound
下限。接受表达式输入。 非表达式输入将被解析为字面量。 如果设置为
None(默认值),则不应用下限。- upper_bound
上限。接受表达式输入。 非表达式输入将被解析为字面量。 如果设置为
None(默认值),则不应用上限。
另请参阅
注释
此方法仅适用于数值和时间列。要裁剪其他数据类型,请考虑编写一个
when-then-otherwise表达式。参见when()。示例
指定下限和上限:
>>> s = pl.Series([-50, 5, 50, None]) >>> s.clip(1, 10) shape: (4,) Series: '' [i64] [ 1 5 10 null ]
仅指定单个边界:
>>> s.clip(upper_bound=10) shape: (4,) Series: '' [i64] [ -50 5 10 null ]
- clone() Self[source]
创建此系列的副本。
这是一个不复制数据的廉价操作。
另请参阅
clear创建一个当前Series的空副本,具有相同的模式但没有数据。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.clone() shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
- cos() Series[source]
计算元素级别的余弦值。
示例
>>> import math >>> s = pl.Series("a", [0.0, math.pi / 2.0, math.pi]) >>> s.cos() shape: (3,) Series: 'a' [f64] [ 1.0 6.1232e-17 -1.0 ]
- cosh() Series[source]
计算双曲余弦的逐元素值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.cosh() shape: (3,) Series: 'a' [f64] [ 1.543081 1.0 1.543081 ]
- cot() Series[source]
计算元素级的余切值。
示例
>>> import math >>> s = pl.Series("a", [0.0, math.pi / 2.0, math.pi]) >>> s.cot() shape: (3,) Series: 'a' [f64] [ inf 6.1232e-17 -8.1656e15 ]
- cum_count(*, reverse: bool = False) Self[source]
返回列中非空值的累计计数。
- Parameters:
- reverse
反转操作。
示例
>>> s = pl.Series(["x", "k", None, "d"]) >>> s.cum_count() shape: (4,) Series: '' [u32] [ 1 2 2 3 ]
- cum_max(*, reverse: bool = False) Series[source]
获取一个数组,其中包含在每个元素处计算的累积最大值。
- Parameters:
- reverse
反转操作。
示例
>>> s = pl.Series("s", [3, 5, 1]) >>> s.cum_max() shape: (3,) Series: 's' [i64] [ 3 5 5 ]
- cum_min(*, reverse: bool = False) Series[source]
获取一个数组,其中包含在每个元素处计算的累积最小值。
- Parameters:
- reverse
反转操作。
示例
>>> s = pl.Series("s", [1, 2, 3]) >>> s.cum_min() shape: (3,) Series: 's' [i64] [ 1 1 1 ]
- cum_prod(*, reverse: bool = False) Series[source]
获取一个数组,其中包含在每个元素处计算的累积乘积。
- Parameters:
- reverse
反转操作。
注释
{Int8, UInt8, Int16, UInt16} 中的数据类型在求和之前会被转换为 Int64,以防止溢出问题。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.cum_prod() shape: (3,) Series: 'a' [i64] [ 1 2 6 ]
- cum_sum(*, reverse: bool = False) Series[source]
获取一个数组,其中每个元素都计算了累积和。
- Parameters:
- reverse
反转操作。
注释
{Int8, UInt8, Int16, UInt16} 中的数据类型在求和之前会被转换为 Int64,以防止溢出问题。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.cum_sum() shape: (3,) Series: 'a' [i64] [ 1 3 6 ]
- cumulative_eval( ) Series[source]
在每次迭代增加
1个槽的滑动窗口上运行表达式。警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- expr
要评估的表达式
- min_periods
在表达式被评估之前,窗口中应该存在的有效值的数量。有效值 =
length - null_count- parallel
并行运行。不要在已经具有大量并行化的分组或其他操作中执行此操作。
警告
这可能会非常慢,因为它可能具有
O(n^2)的复杂度。不要在对所有元素进行操作的场景中使用此方法。示例
>>> s = pl.Series("values", [1, 2, 3, 4, 5]) >>> s.cumulative_eval(pl.element().first() - pl.element().last() ** 2) shape: (5,) Series: 'values' [i64] [ 0 -3 -8 -15 -24 ]
- cut(
- breaks: Sequence[float],
- *,
- labels: Sequence[str] | None = None,
- left_closed: bool = False,
- include_breaks: bool = False,
将连续值分箱为离散类别。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- breaks
唯一分割点的列表。
- labels
类别的名称。标签的数量必须等于切点的数量加一。
- left_closed
将间隔设置为左闭而不是右闭。
- include_breaks
包含一个列,显示每个观察值所属区间的右端点。这将把输出的数据类型从
Categorical更改为Struct。
- Returns:
- Series
如果
include_breaks设置为False(默认),则数据类型为Categorical的Series,否则为数据类型Struct的Series。
另请参阅
示例
将列分为三类。
>>> s = pl.Series("foo", [-2, -1, 0, 1, 2]) >>> s.cut([-1, 1], labels=["a", "b", "c"]) shape: (5,) Series: 'foo' [cat] [ "a" "a" "b" "b" "c" ]
为每个值创建一个包含断点和类别的DataFrame。
>>> cut = s.cut([-1, 1], include_breaks=True).alias("cut") >>> s.to_frame().with_columns(cut).unnest("cut") shape: (5, 3) ┌─────┬────────────┬────────────┐ │ foo ┆ breakpoint ┆ category │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ cat │ ╞═════╪════════════╪════════════╡ │ -2 ┆ -1.0 ┆ (-inf, -1] │ │ -1 ┆ -1.0 ┆ (-inf, -1] │ │ 0 ┆ 1.0 ┆ (-1, 1] │ │ 1 ┆ 1.0 ┆ (-1, 1] │ │ 2 ┆ inf ┆ (1, inf] │ └─────┴────────────┴────────────┘
- describe(
- percentiles: Sequence[float] | float | None = (0.25, 0.5, 0.75),
- interpolation: RollingInterpolationMethod = 'nearest',
系列的快速摘要统计。
包含混合数据类型的Series将返回第一个值的数据类型的汇总统计信息。
- Parameters:
- percentiles
要包含在汇总统计中的一个或多个百分位数(如果Series具有数值类型)。所有值必须在
[0, 1]范围内。- interpolation{‘nearest’, ‘higher’, ‘lower’, ‘midpoint’, ‘linear’}
计算百分位数时使用的插值方法。
- Returns:
- DataFrame
使用Series的摘要统计进行映射。
注释
默认情况下,中位数作为50%百分位数被包含在内。
示例
>>> s = pl.Series([1, 2, 3, 4, 5]) >>> s.describe() shape: (9, 2) ┌────────────┬──────────┐ │ statistic ┆ value │ │ --- ┆ --- │ │ str ┆ f64 │ ╞════════════╪══════════╡ │ count ┆ 5.0 │ │ null_count ┆ 0.0 │ │ mean ┆ 3.0 │ │ std ┆ 1.581139 │ │ min ┆ 1.0 │ │ 25% ┆ 2.0 │ │ 50% ┆ 3.0 │ │ 75% ┆ 4.0 │ │ max ┆ 5.0 │ └────────────┴──────────┘
非数值数据类型可能无法提供所有统计信息。
>>> s = pl.Series(["aa", "aa", None, "bb", "cc"]) >>> s.describe() shape: (4, 2) ┌────────────┬───────┐ │ statistic ┆ value │ │ --- ┆ --- │ │ str ┆ str │ ╞════════════╪═══════╡ │ count ┆ 4 │ │ null_count ┆ 1 │ │ min ┆ aa │ │ max ┆ cc │ └────────────┴───────┘
- diff(n: int = 1, null_behavior: NullBehavior = 'ignore') Series[source]
计算偏移项之间的第一个离散差异。
- Parameters:
- n
要移动的槽位数。
- null_behavior{‘ignore’, ‘drop’}
如何处理空值。
示例
>>> s = pl.Series("s", values=[20, 10, 30, 25, 35], dtype=pl.Int8) >>> s.diff() shape: (5,) Series: 's' [i8] [ null -10 20 -5 10 ]
>>> s.diff(n=2) shape: (5,) Series: 's' [i8] [ null null 10 15 5 ]
>>> s.diff(n=2, null_behavior="drop") shape: (3,) Series: 's' [i8] [ 10 15 5 ]
- dot(other: Series | ArrayLike) int | float | None[source]
计算两个Series之间的点积/内积。
- Parameters:
- other
用于计算点积的Series(或数组)。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s2 = pl.Series("b", [4.0, 5.0, 6.0]) >>> s.dot(s2) 32.0
- drop_nans() Series[source]
删除所有浮点数的NaN值。
剩余元素的原始顺序被保留。
另请参阅
注释
NaN 值与 null 值不同。 要删除 null 值,请使用
drop_nulls()。示例
>>> s = pl.Series([1.0, None, 3.0, float("nan")]) >>> s.drop_nans() shape: (3,) Series: '' [f64] [ 1.0 null 3.0 ]
- drop_nulls() Series[source]
删除所有空值。
剩余元素的原始顺序被保留。
另请参阅
注释
空值(null value)与NaN值不同。 要删除NaN值,请使用
drop_nans()。示例
>>> s = pl.Series([1.0, None, 3.0, float("nan")]) >>> s.drop_nulls() shape: (3,) Series: '' [f64] [ 1.0 3.0 NaN ]
- entropy( ) float | None[source]
计算熵。
使用公式
-sum(pk * log(pk),其中pk是离散概率。- Parameters:
- base
给定基数,默认为
e- normalize
如果pk的总和不为1,则对其进行归一化。
示例
>>> a = pl.Series([0.99, 0.005, 0.005]) >>> a.entropy(normalize=True) 0.06293300616044681 >>> b = pl.Series([0.65, 0.10, 0.25]) >>> b.entropy(normalize=True) 0.8568409950394724
- eq(other: Any) Series | Expr[source]
方法等同于操作符表达式
series == other。
- eq_missing(other: Any) Series | Expr[source]
等同于相等运算符
series == other的方法,其中None == None。这与标准的
eq不同,在标准情况下,空值会被传播。- Parameters:
- other
要与字面量或表达式值进行比较。
另请参阅
示例
>>> s1 = pl.Series("a", [333, 200, None]) >>> s2 = pl.Series("a", [100, 200, None]) >>> s1.eq(s2) shape: (3,) Series: 'a' [bool] [ false true null ] >>> s1.eq_missing(s2) shape: (3,) Series: 'a' [bool] [ false true true ]
- equals( ) bool[source]
检查Series是否等于另一个Series。
- Parameters:
- other
要比较的系列。
- check_dtypes
要求数据类型匹配。
- check_names
要求名称匹配。
- null_equal
将空值视为相等。
示例
>>> s1 = pl.Series("a", [1, 2, 3]) >>> s2 = pl.Series("b", [4, 5, 6]) >>> s1.equals(s1) True >>> s1.equals(s2) False
- estimated_size(unit: SizeUnit = 'b') int | float[source]
返回Series的总(堆)分配大小的估计值。
估计大小以指定单位给出(默认为字节)。
此估计是其缓冲区大小、有效性的总和,包括嵌套数组。多个数组可能共享缓冲区和位图。因此,两个数组的大小不是从此函数计算出的尺寸的总和。特别是,[
StructArray]的大小是一个上限。当数组被切片时,其分配的大小保持不变,因为缓冲区未改变。然而,此函数将返回一个较小的数字。这是因为此函数返回缓冲区的可见大小,而不是其总容量。
FFI缓冲区包含在此估计中。
- Parameters:
- unit{‘b’, ‘kb’, ‘mb’, ‘gb’, ‘tb’}
将返回的大小缩放到给定的单位。
示例
>>> s = pl.Series("values", list(range(1_000_000)), dtype=pl.UInt32) >>> s.estimated_size() 4000000 >>> s.estimated_size("mb") 3.814697265625
- ewm_mean(
- *,
- com: float | None = None,
- span: float | None = None,
- half_life: float | None = None,
- alpha: float | None = None,
- adjust: bool = True,
- min_periods: int = 1,
- ignore_nulls: bool = False,
计算指数加权移动平均。
- Parameters:
- com
以质心为中心指定衰减,\(\gamma\),使用
\[\alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0\]- span
根据跨度\(\theta\)指定衰减
\[\alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1\]- half_life
以半衰期\(\tau\)来指定衰减,使用
\[\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \; \forall \; \tau > 0\]- alpha
直接指定平滑因子alpha,\(0 < \alpha \leq 1\)。
- adjust
在初始阶段通过衰减调整因子进行除法,以考虑相对权重的不平衡
当
adjust=True(默认值)时,EW 函数使用权重 \(w_i = (1 - \alpha)^i\) 计算当
adjust=False时,EW 函数通过递归计算\[\begin{split}y_0 &= x_0 \\ y_t &= (1 - \alpha)y_{t - 1} + \alpha x_t\end{split}\]
- min_periods
窗口中需要的最小观察次数才能有值(否则结果为null)。
- ignore_nulls
在计算权重时忽略缺失值。
当
ignore_nulls=False(默认)时,权重基于绝对位置。 例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \((1-\alpha)^2\) 和 \(1\)(如果adjust=True),以及 \((1-\alpha)^2\) 和 \(\alpha\)(如果adjust=False)。当
ignore_nulls=True时,权重基于相对位置。例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \(1-\alpha\) 和 \(1\)(如果adjust=True),以及 \(1-\alpha\) 和 \(\alpha\)(如果adjust=False)。
示例
>>> s = pl.Series([1, 2, 3]) >>> s.ewm_mean(com=1, ignore_nulls=False) shape: (3,) Series: '' [f64] [ 1.0 1.666667 2.428571 ]
- ewm_mean_by(by: IntoExpr, *, half_life: str | timedelta) Series[source]
计算基于时间的指数加权移动平均。
给定在时间 \(t_0, t_1, \ldots, t_{n-1}\) 的观测值 \(x_0, x_1, \ldots, x_{n-1}\),EWMA 的计算方式为
\[ \begin{align}\begin{aligned}y_0 &= x_0\\\alpha_i &= 1 - \exp \left\{ \frac{ -\ln(2)(t_i-t_{i-1}) } { \tau } \right\}\\y_i &= \alpha_i x_i + (1 - \alpha_i) y_{i-1}; \quad i > 0\end{aligned}\end{align} \]其中 \(\tau\) 是
half_life。- Parameters:
- by
用于计算平均值的时间。应为
DateTime,Date,UInt64,UInt32,Int64, 或Int32数据类型。- half_life
观察值衰减到其一半值的时间单位。
可以从一个时间差创建,或者 通过使用以下字符串语言来创建:
1纳秒 (1 纳秒)
1微秒 (1 微秒)
1毫秒 (1 毫秒)
1秒 (1 秒)
1分钟 (1 minute)
1小时 (1小时)
1天 (1 天)
1周 (1 周)
1i (1 索引计数)
或者将它们组合起来: “3d12h4m25s” # 3天,12小时,4分钟,25秒
请注意,
half_life被视为一个固定的持续时间 - 不支持日历持续时间,如月份(或在时区感知的情况下甚至天数),请以大约等效的小时数表示您的持续时间(例如,使用'370h'而不是'1mo')。
- Returns:
- Expr
如果输入是Float32,则为Float32,否则为Float64。
示例
>>> from datetime import date, timedelta >>> df = pl.DataFrame( ... { ... "values": [0, 1, 2, None, 4], ... "times": [ ... date(2020, 1, 1), ... date(2020, 1, 3), ... date(2020, 1, 10), ... date(2020, 1, 15), ... date(2020, 1, 17), ... ], ... } ... ).sort("times") >>> df["values"].ewm_mean_by(df["times"], half_life="4d") shape: (5,) Series: 'values' [f64] [ 0.0 0.292893 1.492474 null 3.254508 ]
- ewm_std(
- *,
- com: float | None = None,
- span: float | None = None,
- half_life: float | None = None,
- alpha: float | None = None,
- adjust: bool = True,
- bias: bool = False,
- min_periods: int = 1,
- ignore_nulls: bool = False,
计算指数加权移动标准差。
- Parameters:
- com
以质心为中心指定衰减,\(\gamma\),使用
\[\alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0\]- span
根据跨度\(\theta\)指定衰减
\[\alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1\]- half_life
以半衰期\(\lambda\)来指定衰减,
\[\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \lambda } \right\} \; \forall \; \lambda > 0\]- alpha
直接指定平滑因子alpha,\(0 < \alpha \leq 1\)。
- adjust
在初始阶段通过衰减调整因子进行除法,以考虑相对权重的不平衡
当
adjust=True(默认值)时,EW 函数使用权重 \(w_i = (1 - \alpha)^i\) 计算当
adjust=False时,EW 函数通过递归计算\[\begin{split}y_0 &= x_0 \\ y_t &= (1 - \alpha)y_{t - 1} + \alpha x_t\end{split}\]
- bias
当
bias=False时,应用校正以使估计在统计上无偏。- min_periods
窗口中需要的最小观察次数才能有值(否则结果为null)。
- ignore_nulls
在计算权重时忽略缺失值。
当
ignore_nulls=False(默认)时,权重基于绝对位置。 例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \((1-\alpha)^2\) 和 \(1\)(如果adjust=True),以及 \((1-\alpha)^2\) 和 \(\alpha\)(如果adjust=False)。当
ignore_nulls=True时,权重基于相对位置。例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \(1-\alpha\) 和 \(1\)(如果adjust=True),以及 \(1-\alpha\) 和 \(\alpha\)(如果adjust=False)。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.ewm_std(com=1, ignore_nulls=False) shape: (3,) Series: 'a' [f64] [ 0.0 0.707107 0.963624 ]
- ewm_var(
- *,
- com: float | None = None,
- span: float | None = None,
- half_life: float | None = None,
- alpha: float | None = None,
- adjust: bool = True,
- bias: bool = False,
- min_periods: int = 1,
- ignore_nulls: bool = False,
计算指数加权移动方差。
- Parameters:
- com
以质心为中心指定衰减,\(\gamma\),使用
\[\alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0\]- span
根据跨度\(\theta\)指定衰减
\[\alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1\]- half_life
以半衰期\(\lambda\)来指定衰减,
\[\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \lambda } \right\} \; \forall \; \lambda > 0\]- alpha
直接指定平滑因子alpha,\(0 < \alpha \leq 1\)。
- adjust
在初始阶段通过衰减调整因子进行除法,以考虑相对权重的不平衡
当
adjust=True(默认值)时,EW 函数使用权重 \(w_i = (1 - \alpha)^i\) 计算当
adjust=False时,EW 函数通过递归计算\[\begin{split}y_0 &= x_0 \\ y_t &= (1 - \alpha)y_{t - 1} + \alpha x_t\end{split}\]
- bias
当
bias=False时,应用校正以使估计在统计上无偏。- min_periods
窗口中需要的最小观察次数才能有值(否则结果为null)。
- ignore_nulls
在计算权重时忽略缺失值。
当
ignore_nulls=False(默认)时,权重基于绝对位置。 例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \((1-\alpha)^2\) 和 \(1\)(如果adjust=True),以及 \((1-\alpha)^2\) 和 \(\alpha\)(如果adjust=False)。当
ignore_nulls=True时,权重基于相对位置。例如,在计算 [\(x_0\), None, \(x_2\)] 的最终加权平均值时,\(x_0\) 和 \(x_2\) 的权重分别为 \(1-\alpha\) 和 \(1\)(如果adjust=True),或者 \(1-\alpha\) 和 \(\alpha\)(如果adjust=False)。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.ewm_var(com=1, ignore_nulls=False) shape: (3,) Series: 'a' [f64] [ 0.0 0.5 0.928571 ]
- exp() Series[source]
计算指数,逐元素。
示例
>>> s = pl.Series([1, 2, 3]) >>> s.exp() shape: (3,) Series: '' [f64] [ 2.718282 7.389056 20.085537 ]
- explode() Series[source]
展开一个列表系列。
这意味着每个项目都被扩展到一个新行。
- Returns:
- Series
具有列表元素数据类型的系列。
另请参阅
Series.list.explode展开一个列表列。
示例
>>> s = pl.Series("a", [[1, 2, 3], [4, 5, 6]]) >>> s shape: (2,) Series: 'a' [list[i64]] [ [1, 2, 3] [4, 5, 6] ] >>> s.explode() shape: (6,) Series: 'a' [i64] [ 1 2 3 4 5 6 ]
- extend(other: Series) Self[source]
使用另一个Series的值扩展此Series支持的内存。
与
append不同,它将other的块添加到此系列的块中,而extend将other的数据附加到基础内存位置,因此可能会导致重新分配(这是昂贵的)。如果这不会导致重新分配,生成的数据结构将不会有任何额外的块,因此查询速度会更快。
当您希望在单个追加操作后执行查询时,优先使用
extend而不是append。例如,在在线操作期间,您添加n行并重新运行查询。在查询之前需要多次追加时,优先使用
append而不是extend。例如,当您读取多个文件并希望将它们存储在单个Series中时。在后一种情况下,使用rechunk完成append操作序列。- Parameters:
- other
用于扩展系列的系列。
警告
此方法会就地修改序列。返回序列仅为了方便。
另请参阅
示例
>>> a = pl.Series("a", [1, 2, 3]) >>> b = pl.Series("b", [4, 5]) >>> a.extend(b) shape: (5,) Series: 'a' [i64] [ 1 2 3 4 5 ]
结果系列将包含单个块。
>>> a.n_chunks() 1
- extend_constant(value: IntoExpr, n: int | IntoExprColumn) Series[source]
用于使用值的'n'个副本扩展Series的极快方法。
- Parameters:
- value
一个常量字面值或单位表达式,用于扩展表达式结果系列;可以传递None以用空值扩展。
- n
将要添加的额外值的数量。
示例
>>> s = pl.Series([1, 2, 3]) >>> s.extend_constant(99, n=2) shape: (5,) Series: '' [i64] [ 1 2 3 99 99 ]
- fill_nan(value: int | float | Expr | None) Series[source]
用填充值填充浮点数的NaN值。
- Parameters:
- value
用于填充NaN值的值。
警告
请注意,浮点数的NaN(非数字)不是缺失值。 要替换缺失值,请使用
fill_null()。另请参阅
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, float("nan")]) >>> s.fill_nan(0) shape: (4,) Series: 'a' [f64] [ 1.0 2.0 3.0 0.0 ]
- fill_null(
- value: Any | Expr | None = None,
- strategy: FillNullStrategy | None = None,
- limit: int | None = None,
使用指定的值或策略填充空值。
- Parameters:
- value
用于填充空值的值。
- strategy{None, ‘forward’, ‘backward’, ‘min’, ‘max’, ‘mean’, ‘zero’, ‘one’}
用于填充空值的策略。
- limit
使用‘forward’或‘backward’策略时,要填充的连续空值的数量。
另请参阅
示例
>>> s = pl.Series("a", [1, 2, 3, None]) >>> s.fill_null(strategy="forward") shape: (4,) Series: 'a' [i64] [ 1 2 3 3 ] >>> s.fill_null(strategy="min") shape: (4,) Series: 'a' [i64] [ 1 2 3 1 ] >>> s = pl.Series("b", ["x", None, "z"]) >>> s.fill_null(pl.lit("")) shape: (3,) Series: 'b' [str] [ "x" "" "z" ]
- filter(predicate: Series | Iterable[bool]) Self[source]
通过布尔掩码过滤元素。
剩余元素的原始顺序被保留。
过滤器未评估为True的元素将被丢弃,包括空值。
- Parameters:
- predicate
布尔掩码。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> mask = pl.Series("", [True, False, True]) >>> s.filter(mask) shape: (2,) Series: 'a' [i64] [ 1 3 ]
- property flags: dict[str, bool][source]
获取在Series上设置的标志。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.flags {'SORTED_ASC': False, 'SORTED_DESC': False}
- floor() Series[source]
向下舍入到最接近的整数值。
仅适用于浮点型Series。
示例
>>> s = pl.Series("a", [1.12345, 2.56789, 3.901234]) >>> s.floor() shape: (3,) Series: 'a' [f64] [ 1.0 2.0 3.0 ]
- gather(indices: int | list[int] | Expr | Series | np.ndarray[Any, Any]) Series[source]
按索引取值。
- Parameters:
- indices
用于选择的索引位置。
示例
>>> s = pl.Series("a", [1, 2, 3, 4]) >>> s.gather([1, 3]) shape: (2,) Series: 'a' [i64] [ 2 4 ]
- gather_every(n: int, offset: int = 0) Series[source]
取Series中的每第n个值并返回为新的Series。
- Parameters:
- n
收集每n行。
- offset
从这个偏移量开始行索引。
示例
>>> s = pl.Series("a", [1, 2, 3, 4]) >>> s.gather_every(2) shape: (2,) Series: 'a' [i64] [ 1 3 ] >>> s.gather_every(2, offset=1) shape: (2,) Series: 'a' [i64] [ 2 4 ]
- ge(other: Any) Series | Expr[source]
方法等同于操作符表达式
series >= other。
- get_chunks() list[Series][source]
获取此Series的块作为Series列表。
示例
>>> s1 = pl.Series("a", [1, 2, 3]) >>> s2 = pl.Series("a", [4, 5, 6]) >>> s = pl.concat([s1, s2], rechunk=False) >>> s.get_chunks() [shape: (3,) Series: 'a' [i64] [ 1 2 3 ], shape: (3,) Series: 'a' [i64] [ 4 5 6 ]]
- gt(other: Any) Series | Expr[source]
方法等同于操作符表达式
series > other。
- has_nulls() bool[source]
检查Series是否包含一个或多个空值。
示例
>>> s = pl.Series([1, 2, None]) >>> s.has_nulls() True >>> s[:2].has_nulls() False
- has_validity() bool[source]
检查Series是否包含一个或多个空值。
自版本0.20.30起已弃用:请改用
has_nulls()。
- hash( ) Series[source]
哈希系列。
哈希值的类型为
UInt64。- Parameters:
- seed
随机种子参数。默认为0。
- seed_1
随机种子参数。如果未设置,默认为
seed。- seed_2
随机种子参数。如果未设置,默认为
seed。- seed_3
随机种子参数。如果未设置,默认为
seed。
注释
此
hash的实现不保证在不同Polars版本之间的结果稳定性。其稳定性仅在单个版本内得到保证。示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.hash(seed=42) shape: (3,) Series: 'a' [u64] [ 10734580197236529959 3022416320763508302 13756996518000038261 ]
- head(n: int = 10) Series[source]
获取前
n个元素。- Parameters:
- n
返回的元素数量。如果传递了一个负值,则返回除最后
abs(n)个元素之外的所有元素。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.head(3) shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
传递一个负值以获取除最后
abs(n)行之外的所有行。>>> s.head(-3) shape: (2,) Series: 'a' [i64] [ 1 2 ]
- hist(
- bins: list[float] | None = None,
- *,
- bin_count: int | None = None,
- include_category: bool = True,
- include_breakpoint: bool = True,
将值分入桶中并计算它们的出现次数。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- bins
需要进行的离散化处理。 如果未给出,我们将根据数据确定边界。
- bin_count
如果没有提供bins,这将用于确定bins的距离。
- include_breakpoint
包含一个指示上断点的列。
- include_category
包含一个显示区间为类别的列。
- Returns:
- DataFrame
示例
>>> a = pl.Series("a", [1, 3, 8, 8, 2, 1, 3]) >>> a.hist(bin_count=4) shape: (4, 3) ┌────────────┬───────────────┬───────┐ │ breakpoint ┆ category ┆ count │ │ --- ┆ --- ┆ --- │ │ f64 ┆ cat ┆ u32 │ ╞════════════╪═══════════════╪═══════╡ │ 2.75 ┆ (0.993, 2.75] ┆ 3 │ │ 4.5 ┆ (2.75, 4.5] ┆ 2 │ │ 6.25 ┆ (4.5, 6.25] ┆ 0 │ │ 8.0 ┆ (6.25, 8.0] ┆ 2 │ └────────────┴───────────────┴───────┘
- implode() Self[source]
将值聚合到一个列表中。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.implode() shape: (1,) Series: 'a' [list[i64]] [ [1, 2, 3] ]
- interpolate(method: InterpolationMethod = 'linear') Series[source]
使用插值填充空值。
- Parameters:
- method{‘linear’, ‘nearest’}
插值方法。
示例
>>> s = pl.Series("a", [1, 2, None, None, 5]) >>> s.interpolate() shape: (5,) Series: 'a' [f64] [ 1.0 2.0 3.0 4.0 5.0 ]
- interpolate_by(by: IntoExpr) Series[source]
使用基于另一列的插值来填充空值。
- Parameters:
- by
基于插值的列。
示例
使用线性插值填充空值。
>>> s = pl.Series([1, None, None, 3]) >>> by = pl.Series([1, 2, 7, 8]) >>> s.interpolate_by(by) shape: (4,) Series: '' [f64] [ 1.0 1.285714 2.714286 3.0 ]
- is_between(
- lower_bound: IntoExpr,
- upper_bound: IntoExpr,
- closed: ClosedInterval = 'both',
获取一个布尔掩码,表示值是否在给定的下限/上限之间。
- Parameters:
- lower_bound
下限值。接受表达式输入。非表达式输入(包括字符串)将被解析为字面量。
- upper_bound
上限值。接受表达式输入。非表达式输入(包括字符串)将被解析为字面量。
- closed{‘both’, ‘left’, ‘right’, ‘none’}
定义区间的哪些边是闭合的(包含的)。
注释
如果
lower_bound的值大于upper_bound的值,那么结果将为False,因为没有值可以满足条件。示例
>>> s = pl.Series("num", [1, 2, 3, 4, 5]) >>> s.is_between(2, 4) shape: (5,) Series: 'num' [bool] [ false true true true false ]
使用
closed参数来包含或排除边界值:>>> s.is_between(2, 4, closed="left") shape: (5,) Series: 'num' [bool] [ false true true false false ]
你也可以使用字符串以及数字/时间值:
>>> s = pl.Series("s", ["a", "b", "c", "d", "e"]) >>> s.is_between("b", "d", closed="both") shape: (5,) Series: 's' [bool] [ false true true true false ]
- is_duplicated() Series[source]
获取所有重复值的掩码。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.is_duplicated() shape: (4,) Series: 'a' [bool] [ false true true false ]
- is_empty() bool[source]
检查Series是否为空。
示例
>>> s = pl.Series("a", [], dtype=pl.Float32) >>> s.is_empty() True
- is_finite() Series[source]
返回一个布尔系列,指示哪些值是有限的。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> import numpy as np >>> s = pl.Series("a", [1.0, 2.0, np.inf]) >>> s.is_finite() shape: (3,) Series: 'a' [bool] [ true true false ]
- is_first_distinct() Series[source]
返回一个布尔掩码,指示每个不同值的首次出现。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series([1, 1, 2, 3, 2]) >>> s.is_first_distinct() shape: (5,) Series: '' [bool] [ true false true true false ]
- is_in(other: Series | Collection[Any]) Series[source]
检查此系列中的元素是否在另一个系列中。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s2 = pl.Series("b", [2, 4]) >>> s2.is_in(s) shape: (2,) Series: 'b' [bool] [ true false ]
>>> # check if some values are a member of sublists >>> sets = pl.Series("sets", [[1, 2, 3], [1, 2], [9, 10]]) >>> optional_members = pl.Series("optional_members", [1, 2, 3]) >>> print(sets) shape: (3,) Series: 'sets' [list[i64]] [ [1, 2, 3] [1, 2] [9, 10] ] >>> print(optional_members) shape: (3,) Series: 'optional_members' [i64] [ 1 2 3 ] >>> optional_members.is_in(sets) shape: (3,) Series: 'optional_members' [bool] [ true true false ]
- is_infinite() Series[source]
返回一个布尔系列,指示哪些值是无限的。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> import numpy as np >>> s = pl.Series("a", [1.0, 2.0, np.inf]) >>> s.is_infinite() shape: (3,) Series: 'a' [bool] [ false false true ]
- is_last_distinct() Series[source]
返回一个布尔掩码,指示每个不同值的最后一次出现。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series([1, 1, 2, 3, 2]) >>> s.is_last_distinct() shape: (5,) Series: '' [bool] [ false true false true true ]
- is_nan() Series[source]
返回一个布尔系列,指示哪些值是NaN。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> import numpy as np >>> s = pl.Series("a", [1.0, 2.0, 3.0, np.nan]) >>> s.is_nan() shape: (4,) Series: 'a' [bool] [ false false false true ]
- is_not_nan() Series[source]
返回一个布尔系列,指示哪些值不是NaN。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> import numpy as np >>> s = pl.Series("a", [1.0, 2.0, 3.0, np.nan]) >>> s.is_not_nan() shape: (4,) Series: 'a' [bool] [ true true true false ]
- is_not_null() Series[source]
返回一个布尔系列,指示哪些值不为空。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, None]) >>> s.is_not_null() shape: (4,) Series: 'a' [bool] [ true true true false ]
- is_null() Series[source]
返回一个布尔系列,指示哪些值为空。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, None]) >>> s.is_null() shape: (4,) Series: 'a' [bool] [ false false false true ]
- is_sorted(*, descending: bool = False, nulls_last: bool = False) bool[source]
检查Series是否已排序。
- Parameters:
- descending
检查Series是否按降序排序
- nulls_last
在排序检查中将Series末尾的空值设置为空。
示例
>>> s = pl.Series([1, 3, 2]) >>> s.is_sorted() False
>>> s = pl.Series([3, 2, 1]) >>> s.is_sorted(descending=True) True
- is_unique() Series[source]
获取所有唯一值的掩码。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.is_unique() shape: (4,) Series: 'a' [bool] [ true false false true ]
- item(index: int | None = None) Any[source]
将Series作为标量返回,或返回给定索引处的元素。
如果没有提供索引,这相当于
s[0],并检查形状是否为(1,)。如果提供了索引,这相当于s[index]。示例
>>> s1 = pl.Series("a", [1]) >>> s1.item() 1 >>> s2 = pl.Series("a", [9, 8, 7]) >>> s2.cum_sum().item(-1) 24
- kurtosis(*, fisher: bool = True, bias: bool = True) float | None[source]
计算数据集的峰度(Fisher 或 Pearson)。
峰度是第四中心矩除以方差的平方。如果使用费舍尔的定义,则从结果中减去3.0,以使正态分布的峰度为0.0。如果bias为False,则使用k统计量计算峰度,以消除来自有偏矩估计器的偏差。
有关更多信息,请参阅 scipy.stats
- Parameters:
- fisherbool, optional
如果为True,则使用Fisher的定义(正常 ==> 0.0)。如果为False,则使用Pearson的定义(正常 ==> 3.0)。
- biasbool, optional
如果为False,则计算会针对统计偏差进行校正。
示例
>>> s = pl.Series("grades", [66, 79, 54, 97, 96, 70, 69, 85, 93, 75]) >>> s.kurtosis() -1.0522623626787952 >>> s.kurtosis(fisher=False) 1.9477376373212048 >>> s.kurtosis(fisher=False, bias=False) 2.1040361802642726
- le(other: Any) Series | Expr[source]
方法等同于操作符表达式
series <= other。
- len() int[source]
返回Series中的元素数量。
空值计入总数。
另请参阅
示例
>>> s = pl.Series("a", [1, 2, None]) >>> s.len() 3
- limit(n: int = 10) Series[source]
获取前
n个元素。Series.head()的别名。- Parameters:
- n
返回的元素数量。如果传递了一个负值,则返回除最后
abs(n)个元素之外的所有元素。
另请参阅
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.limit(3) shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
传递一个负值以获取除最后
abs(n)行之外的所有行。>>> s.limit(-3) shape: (2,) Series: 'a' [i64] [ 1 2 ]
- log(base: float = 2.718281828459045) Series[source]
计算给定底数的对数。
示例
>>> s = pl.Series([1, 2, 3]) >>> s.log() shape: (3,) Series: '' [f64] [ 0.0 0.693147 1.098612 ]
- log10() Series[source]
计算输入数组的以10为底的对数,逐元素进行。
示例
>>> s = pl.Series([10, 100, 1000]) >>> s.log10() shape: (3,) Series: '' [f64] [ 1.0 2.0 3.0 ]
- log1p() Series[source]
计算输入数组加一的自然对数,逐元素进行。
示例
>>> s = pl.Series([1, 2, 3]) >>> s.log1p() shape: (3,) Series: '' [f64] [ 0.693147 1.098612 1.386294 ]
- lower_bound() Self[source]
返回此Series数据类型的下限作为一个单位Series。
另请参阅
upper_bound返回给定Series数据类型的上限。
示例
>>> s = pl.Series("s", [-1, 0, 1], dtype=pl.Int32) >>> s.lower_bound() shape: (1,) Series: 's' [i32] [ -2147483648 ]
>>> s = pl.Series("s", [1.0, 2.5, 3.0], dtype=pl.Float32) >>> s.lower_bound() shape: (1,) Series: 's' [f32] [ -inf ]
- lt(other: Any) Series | Expr[source]
方法等同于操作符表达式
series < other。
- map_elements(
- function: Callable[[Any], Any],
- return_dtype: PolarsDataType | None = None,
- *,
- skip_nulls: bool = True,
在此系列的元素上映射自定义/用户定义的函数(UDF)。
警告
此方法比原生表达式API慢得多。 只有在无法以其他方式实现逻辑时才使用它。
假设函数是:
x ↦ sqrt(x):对于映射系列的元素,考虑:
s.sqrt()。对于映射列表的内部元素,考虑:
s.list.eval(pl.element().sqrt())。对于映射结构体字段的元素,考虑:
s.struct.field("field_name").sqrt()。
如果函数返回不同的数据类型,则应设置 return_dtype 参数,否则该方法将失败。
使用Python函数实现逻辑几乎总是比使用原生表达式API实现相同逻辑显著更慢且更占用内存,因为:
原生表达式引擎在Rust中运行;UDFs在Python中运行。
使用Python UDFs会强制将DataFrame物化在内存中。
Polars原生表达式可以并行化(UDF通常不能)。
Polars原生表达式可以进行逻辑优化(UDF则不能)。
在可能的情况下,您应该强烈倾向于使用原生表达式API以实现最佳性能。
- Parameters:
- function
自定义函数或lambda。
- return_dtype
输出数据类型。 如果未设置,将根据函数返回的第一个非空值推断数据类型。
- skip_nulls
空值将被跳过,不会传递给Python函数。 这样更快,因为可以跳过Python,并且我们调用 更专门的函数。
- Returns:
- Series
警告
如果未提供
return_dtype,可能会导致意外结果。 我们允许这种情况,但这被视为用户查询中的错误。注释
如果你的函数计算成本高,并且你不希望它在给定输入时被多次调用,考虑对其应用
@lru_cache装饰器。如果你的数据适合,你可能会实现显著的加速。示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.map_elements(lambda x: x + 10, return_dtype=pl.Int64) shape: (3,) Series: 'a' [i64] [ 11 12 13 ]
- mean() PythonLiteral | None[source]
将此系列减少到平均值。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.mean() 2.0
- median() PythonLiteral | None[source]
获取此系列的中位数。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.median() 2.0
- mode() Series[source]
计算出现频率最高的值。
可以返回多个值。
示例
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.mode() shape: (1,) Series: 'a' [i64] [ 2 ]
- n_chunks() int[source]
获取此系列包含的块数。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.n_chunks() 1 >>> s2 = pl.Series("a", [4, 5, 6])
串联Series,设置rechunk = True
>>> pl.concat([s, s2], rechunk=True).n_chunks() 1
串联Series,rechunk = False
>>> pl.concat([s, s2], rechunk=False).n_chunks() 2
- nan_max() int | float | date | datetime | timedelta | str[source]
获取最大值,但传播/污染遇到的NaN值。
这与numpy的
nanmax不同,因为numpy默认传播NaN值,而polars默认忽略它们。示例
>>> s = pl.Series("a", [1, 3, 4]) >>> s.nan_max() 4
>>> s = pl.Series("a", [1.0, float("nan"), 4.0]) >>> s.nan_max() nan
- nan_min() int | float | date | datetime | timedelta | str[source]
获取最小值,但传播/污染遇到的NaN值。
这与numpy的
nanmax不同,因为numpy默认传播NaN值,而polars默认忽略它们。示例
>>> s = pl.Series("a", [1, 3, 4]) >>> s.nan_min() 1
>>> s = pl.Series("a", [1.0, float("nan"), 4.0]) >>> s.nan_min() nan
- ne(other: Any) Series | Expr[source]
方法等同于操作符表达式
series != other。
- ne_missing(other: Any) Series | Expr[source]
等价于相等运算符
series != other的方法,其中None == None。这与标准的
ne不同,在标准情况下,空值会被传播。- Parameters:
- other
要与字面量或表达式值进行比较。
另请参阅
示例
>>> s1 = pl.Series("a", [333, 200, None]) >>> s2 = pl.Series("a", [100, 200, None]) >>> s1.ne(s2) shape: (3,) Series: 'a' [bool] [ true false null ] >>> s1.ne_missing(s2) shape: (3,) Series: 'a' [bool] [ true false false ]
- new_from_index(index: int, length: int) Self[source]
创建一个新的Series,并用给定索引的值填充。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.new_from_index(1, 3) shape: (3,) Series: 'a' [i64] [ 2 2 2 ]
- not_() Series[source]
对布尔系列进行取反。
- Returns:
- Series
数据类型为
Boolean的系列。
示例
>>> s = pl.Series("a", [True, False, False]) >>> s.not_() shape: (3,) Series: 'a' [bool] [ false true true ]
- pct_change(n: int | IntoExprColumn = 1) Series[source]
计算值之间的百分比变化。
当前元素与至少
n个周期之前的最远非空元素之间的百分比变化(以分数表示)。默认情况下计算与前一行的变化。
- Parameters:
- n
用于形成百分比变化的周期偏移。
示例
>>> pl.Series(range(10)).pct_change() shape: (10,) Series: '' [f64] [ null inf 1.0 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 ]
>>> pl.Series([1, 2, 4, 8, 16, 32, 64, 128, 256, 512]).pct_change(2) shape: (10,) Series: '' [f64] [ null null 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 ]
- peak_max() Self[source]
获取局部最大峰的布尔掩码。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.peak_max() shape: (5,) Series: 'a' [bool] [ false false false false true ]
- peak_min() Self[source]
获取局部最小峰的布尔掩码。
示例
>>> s = pl.Series("a", [4, 1, 3, 2, 5]) >>> s.peak_min() shape: (5,) Series: 'a' [bool] [ false true false true false ]
- property plot: SeriesPlot[source]
创建一个绘图命名空间。
警告
此功能目前被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
在版本1.6.0中更改:在Polars的早期版本中,HvPlot是绘图后端。如果您想恢复以前的绘图功能,您只需要在脚本的顶部添加
import hvplot.polars,并将df.plot替换为df.hvplot。Polars 本身不实现绘图逻辑,而是依赖于 Altair:
s.plot.hist(**kwargs)是alt.Chart(s.to_frame()).mark_bar(tooltip=True).encode(x=alt.X(f'{s.name}:Q', bin=True), y='count()', **kwargs).interactive()的简写s.plot.kde(**kwargs)是alt.Chart(s.to_frame()).transform_density(s.name, as_=[s.name, 'density']).mark_area(tooltip=True).encode(x=s.name, y='density:Q', **kwargs).interactive()的简写对于任何其他属性
attr,s.plot.attr(**kwargs)是alt.Chart(s.to_frame().with_row_index()).mark_attr(tooltip=True).encode(x='index', y=s.name, **kwargs).interactive()的简写
对于配置,我们建议阅读 图表配置。 例如,您可以:
使用
.properties(width=500, height=350, title="My amazing plot")更改宽度/高度/标题。使用
.configure_axisX(labelAngle=30)更改 x 轴标签的旋转角度。使用
.configure_point(opacity=.5)更改散点图中点的透明度。
示例
直方图:
>>> s = pl.Series([1, 4, 4, 6, 2, 4, 3, 5, 5, 7, 1]) >>> s.plot.hist()
KDE 图:
>>> s.plot.kde()
折线图:
>>> s.plot.line()
- pow( ) Series[source]
将给定的指数提升到幂。
如果指数是浮点数,结果遵循指数的dtype。 否则,它遵循基数的dtype。
- Parameters:
- exponent
指数。接受Series输入。
示例
将整数提升为正整数会得到整数:
>>> s = pl.Series("foo", [1, 2, 3, 4]) >>> s.pow(3) shape: (4,) Series: 'foo' [i64] [ 1 8 27 64 ]
为了将整数提升为负整数,你可以将基数或指数转换为浮点数:
>>> s.pow(-3.0) shape: (4,) Series: 'foo' [f64] [ 1.0 0.125 0.037037 0.015625 ]
- qcut(
- quantiles: Sequence[float] | int,
- *,
- labels: Sequence[str] | None = None,
- left_closed: bool = False,
- allow_duplicates: bool = False,
- include_breaks: bool = False,
将连续值根据其分位数分箱到离散类别中。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- quantiles
要么是0到1之间的分位数概率列表,要么是确定具有均匀概率的箱数的正整数。
- labels
类别的名称。标签的数量必须等于切点的数量加一。
- left_closed
将间隔设置为左闭而不是右闭。
- allow_duplicates
如果设置为
True,结果中的重复分位数将被删除,而不是引发DuplicateError。即使概率是唯一的,这种情况也可能发生,具体取决于数据。- include_breaks
包含一个列,显示每个观察值所属区间的右端点。这将把输出的数据类型从
Categorical更改为Struct。
- Returns:
- Series
如果
include_breaks设置为False(默认),则数据类型为Categorical的Series,否则为数据类型Struct的Series。
另请参阅
示例
根据预定义的分位数概率将列分为三类。
>>> s = pl.Series("foo", [-2, -1, 0, 1, 2]) >>> s.qcut([0.25, 0.75], labels=["a", "b", "c"]) shape: (5,) Series: 'foo' [cat] [ "a" "a" "b" "b" "c" ]
使用均匀分位数概率将列分为两类。
>>> s.qcut(2, labels=["low", "high"], left_closed=True) shape: (5,) Series: 'foo' [cat] [ "low" "low" "high" "high" "high" ]
为每个值创建一个包含断点和类别的DataFrame。
>>> cut = s.qcut([0.25, 0.75], include_breaks=True).alias("cut") >>> s.to_frame().with_columns(cut).unnest("cut") shape: (5, 3) ┌─────┬────────────┬────────────┐ │ foo ┆ breakpoint ┆ category │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ cat │ ╞═════╪════════════╪════════════╡ │ -2 ┆ -1.0 ┆ (-inf, -1] │ │ -1 ┆ -1.0 ┆ (-inf, -1] │ │ 0 ┆ 1.0 ┆ (-1, 1] │ │ 1 ┆ 1.0 ┆ (-1, 1] │ │ 2 ┆ inf ┆ (1, inf] │ └─────┴────────────┴────────────┘
- quantile(
- quantile: float,
- interpolation: RollingInterpolationMethod = 'nearest',
获取此系列的分位数值。
- Parameters:
- quantile
分位数在0.0到1.0之间。
- interpolation{‘nearest’, ‘higher’, ‘lower’, ‘midpoint’, ‘linear’}
插值方法。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.quantile(0.5) 2.0
- rank( ) Series[source]
为数据分配排名,适当处理并列情况。
- Parameters:
- method{‘average’, ‘min’, ‘max’, ‘dense’, ‘ordinal’, ‘random’}
用于为相同元素分配排名的方法。 以下方法可用(默认为‘average’):
‘average’ : 将分配给所有相同值的排名的平均值分配给每个值。
'min':将分配给所有相同值的最小排名分配给每个值。(这也被称为“竞争”排名。)
‘max’ : 将分配给所有相同值的最大排名分配给每个值。
‘dense’:类似于‘min’,但下一个最高元素的排名被分配为紧接在那些被分配给并列元素的排名之后。
‘ordinal’ : 所有值都被赋予一个独特的排名,对应于值在Series中出现的顺序。
‘random’ : 类似于‘ordinal’,但对于相同值的排名不依赖于它们在Series中出现的顺序。
- descending
按降序排列。
- seed
如果
method="random",使用此作为种子。
示例
‘average’ 方法:
>>> s = pl.Series("a", [3, 6, 1, 1, 6]) >>> s.rank() shape: (5,) Series: 'a' [f64] [ 3.0 4.5 1.5 1.5 4.5 ]
‘ordinal’ 方法:
>>> s = pl.Series("a", [3, 6, 1, 1, 6]) >>> s.rank("ordinal") shape: (5,) Series: 'a' [u32] [ 3 4 1 2 5 ]
- rechunk(*, in_place: bool = False) Self[source]
为这个系列创建一个单一的内存块。
- Parameters:
- in_place
是否在原位。
示例
>>> s1 = pl.Series("a", [1, 2, 3]) >>> s1.n_chunks() 1 >>> s2 = pl.Series("a", [4, 5, 6]) >>> s = pl.concat([s1, s2], rechunk=False) >>> s.n_chunks() 2 >>> s.rechunk(in_place=True) shape: (6,) Series: 'a' [i64] [ 1 2 3 4 5 6 ] >>> s.n_chunks() 1
- reinterpret(*, signed: bool = True) Series[source]
将底层位重新解释为有符号/无符号整数。
此操作仅允许用于64位整数。对于较低位的整数,您可以安全地使用该转换操作。
- Parameters:
- signed
如果为True,则重新解释为
pl.Int64。否则,重新解释为pl.UInt64。
示例
>>> s = pl.Series("a", [-(2**60), -2, 3]) >>> s shape: (3,) Series: 'a' [i64] [ -1152921504606846976 -2 3 ] >>> s.reinterpret(signed=False) shape: (3,) Series: 'a' [u64] [ 17293822569102704640 18446744073709551614 3 ]
- rename(name: str) Series[source]
重命名此系列。
Series.alias()的别名。- Parameters:
- name
新名称。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.rename("b") shape: (3,) Series: 'b' [i64] [ 1 2 3 ]
- replace(old: IntoExpr | Sequence[Any] | Mapping[Any, Any], new: IntoExpr | Sequence[Any] | NoDefault = <no_default>, *, default: IntoExpr | NoDefault = <no_default>, return_dtype: PolarsDataType | None = None) Self[source]
用相同数据类型的其他值替换值。
- Parameters:
- old
要替换的值或值的序列。 也接受将值映射到它们的替换作为语法糖,用于
replace(old=Series(mapping.keys()), new=Series(mapping.values()))。- new
要替换的值或值的序列。 长度必须与
old的长度匹配或长度为1。- default
将未替换的值设置为此值。 默认情况下保留原始值。 接受表达式输入。非表达式输入将被解析为字面量。
自版本0.20.31起已弃用:请使用
replace_all()来在替换值时设置默认值。- return_dtype
结果表达式的数据类型。如果设置为
None(默认值),则数据类型将根据其他输入自动确定。自版本0.20.31起已弃用:请改用
replace_all()来设置返回数据类型,同时替换值。
注释
在替换分类值时,必须启用全局字符串缓存。
示例
用一个值替换另一个值。未被替换的值保持不变。
>>> s = pl.Series([1, 2, 2, 3]) >>> s.replace(2, 100) shape: (4,) Series: '' [i64] [ 1 100 100 3 ]
通过将序列传递给
old和new参数来替换多个值。>>> s.replace([2, 3], [100, 200]) shape: (4,) Series: '' [i64] [ 1 100 100 200 ]
传递带有替换的映射也作为语法糖支持。
>>> mapping = {2: 100, 3: 200} >>> s.replace(mapping) shape: (4,) Series: '' [i64] [ 1 100 100 200 ]
当用不同数据类型替换时,原始数据类型保持不变。使用
replace_strict()来替换并更改返回的数据类型。>>> s = pl.Series(["x", "y", "z"]) >>> mapping = {"x": 1, "y": 2, "z": 3} >>> s.replace(mapping) shape: (3,) Series: '' [str] [ "1" "2" "3" ]
- replace_strict(old: IntoExpr | Sequence[Any] | Mapping[Any, Any], new: IntoExpr | Sequence[Any] | NoDefault = <no_default>, *, default: IntoExpr | NoDefault = <no_default>, return_dtype: PolarsDataType | None = None) Self[source]
用不同的值替换所有值。
- Parameters:
- old
要替换的值或值的序列。 也可以接受一个值到其替换的映射,作为
replace_all(old=Series(mapping.keys()), new=Series(mapping.values()))的语法糖。- new
要替换的值或值的序列。 长度必须与
old的长度匹配或长度为1。- default
将未替换的值设置为此值。如果未指定默认值(默认情况下),如果任何值未被替换,则会引发错误。接受表达式输入。非表达式输入将被解析为字面量。
- return_dtype
结果Series的数据类型。如果设置为
None(默认值),则数据类型将根据其他输入自动确定。
- Raises:
- InvalidOperationError
如果原始列中的任何非空值未被替换,且未指定
default。
另请参阅
注释
在替换分类值时,必须启用全局字符串缓存。
示例
通过将序列传递给
old和new参数来替换值。>>> s = pl.Series([1, 2, 2, 3]) >>> s.replace_strict([1, 2, 3], [100, 200, 300]) shape: (4,) Series: '' [i64] [ 100 200 200 300 ]
传递带有替换的映射也作为语法糖支持。
>>> mapping = {1: 100, 2: 200, 3: 300} >>> s.replace_strict(mapping) shape: (4,) Series: '' [i64] [ 100 200 200 300 ]
默认情况下,如果任何非空值未被替换,则会引发错误。 指定一个默认值以设置所有未匹配的值。
>>> mapping = {2: 200, 3: 300} >>> s.replace_strict(mapping) Traceback (most recent call last): ... polars.exceptions.InvalidOperationError: incomplete mapping specified for `replace_strict` >>> s.replace_strict(mapping, default=-1) shape: (4,) Series: '' [i64] [ -1 200 200 300 ]
默认值可以是另一个Series。
>>> default = pl.Series([2.5, 5.0, 7.5, 10.0]) >>> s.replace_strict(2, 200, default=default) shape: (4,) Series: '' [f64] [ 2.5 200.0 200.0 10.0 ]
通过不同数据类型的值替换,基于
new数据类型和default数据类型的组合设置返回类型。>>> s = pl.Series(["x", "y", "z"]) >>> mapping = {"x": 1, "y": 2, "z": 3} >>> s.replace_strict(mapping) shape: (3,) Series: '' [i64] [ 1 2 3 ] >>> s.replace_strict(mapping, default="x") shape: (3,) Series: '' [str] [ "1" "2" "3" ]
设置
return_dtype参数以直接控制结果的数据类型。>>> s.replace_strict(mapping, return_dtype=pl.UInt8) shape: (3,) Series: '' [u8] [ 1 2 3 ]
- reshape(dimensions: tuple[int, ...]) Series[source]
将此系列重塑为扁平系列或数组系列。
- Parameters:
- dimensions
维度大小的元组。如果在任何维度中使用-1,则该维度将被推断。
- Returns:
- Series
如果给出单个维度,结果将是原始数据类型的Series。 如果给出多个维度,结果将是数据类型为
Array的Series,形状为dimensions。
另请参阅
Series.list.explode展开一个列表列。
示例
>>> s = pl.Series("foo", [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> square = s.reshape((3, 3)) >>> square shape: (3,) Series: 'foo' [array[i64, 3]] [ [1, 2, 3] [4, 5, 6] [7, 8, 9] ] >>> square.reshape((9,)) shape: (9,) Series: 'foo' [i64] [ 1 2 3 4 5 6 7 8 9 ]
- reverse() Series[source]
返回反向排序的Series。
示例
>>> s = pl.Series("a", [1, 2, 3], dtype=pl.Int8) >>> s.reverse() shape: (3,) Series: 'a' [i8] [ 3 2 1 ]
- rle() Series[source]
使用游程编码压缩Series数据。
游程编码(RLE)通过将每个相同值的游程存储为单个值及其长度来编码数据。
- Returns:
- Series
数据类型为
Struct的系列,包含数据类型为UInt32的字段len和原始数据类型的字段value。
示例
>>> s = pl.Series("s", [1, 1, 2, 1, None, 1, 3, 3]) >>> s.rle().struct.unnest() shape: (6, 2) ┌─────┬───────┐ │ len ┆ value │ │ --- ┆ --- │ │ u32 ┆ i64 │ ╞═════╪═══════╡ │ 2 ┆ 1 │ │ 1 ┆ 2 │ │ 1 ┆ 1 │ │ 1 ┆ null │ │ 1 ┆ 1 │ │ 2 ┆ 3 │ └─────┴───────┘
- rle_id() Series[source]
为每次运行的相同值获取一个唯一的整数ID。
ID从0开始,每次列的值发生变化时增加1。
- Returns:
- Series
数据类型为
UInt32的系列。
另请参阅
注释
此功能特别适用于每次列的值发生变化时定义一个新组,而不是为该列的每个不同值定义新组。
示例
>>> s = pl.Series("s", [1, 1, 2, 1, None, 1, 3, 3]) >>> s.rle_id() shape: (8,) Series: 's' [u32] [ 0 0 1 2 3 4 5 5 ]
- rolling_map(
- function: Callable[[Series], Any],
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
计算自定义滚动窗口函数。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- function
自定义聚合函数。
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
警告
计算自定义函数非常慢。如果可能的话,请使用专门的滚动函数,例如
Series.rolling_sum()。示例
>>> from numpy import nansum >>> s = pl.Series([11.0, 2.0, 9.0, float("nan"), 8.0]) >>> s.rolling_map(nansum, window_size=3) shape: (5,) Series: '' [f64] [ null null 22.0 11.0 17.0 ]
- rolling_max(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
对此数组中的值应用滚动最大值(移动最大值)。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将聚合为其最大值。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [100, 200, 300, 400, 500]) >>> s.rolling_max(window_size=2) shape: (5,) Series: 'a' [i64] [ null 200 300 400 500 ]
- rolling_mean(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
对此数组中的值应用滚动平均值(移动平均值)。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将被聚合为其平均值。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [100, 200, 300, 400, 500]) >>> s.rolling_mean(window_size=2) shape: (5,) Series: 'a' [f64] [ null 150.0 250.0 350.0 450.0 ]
- rolling_median(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
计算滚动中位数。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0]) >>> s.rolling_median(window_size=3) shape: (6,) Series: 'a' [f64] [ null null 2.0 3.0 4.0 6.0 ]
- rolling_min(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
对此数组中的值应用滚动最小值(移动最小值)。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将被聚合为其最小值。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [100, 200, 300, 400, 500]) >>> s.rolling_min(window_size=3) shape: (5,) Series: 'a' [i64] [ null null 100 200 300 ]
- rolling_quantile(
- quantile: float,
- interpolation: RollingInterpolationMethod = 'nearest',
- window_size: int = 2,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
计算滚动分位数。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- quantile
分位数在0.0到1.0之间。
- interpolation{‘nearest’, ‘higher’, ‘lower’, ‘midpoint’, ‘linear’}
插值方法。
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0]) >>> s.rolling_quantile(quantile=0.33, window_size=3) shape: (6,) Series: 'a' [f64] [ null null 1.0 2.0 3.0 4.0 ] >>> s.rolling_quantile(quantile=0.33, interpolation="linear", window_size=3) shape: (6,) Series: 'a' [f64] [ null null 1.66 2.66 3.66 5.32 ]
- rolling_skew( ) Series[source]
计算滚动偏度。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
给定行的窗口包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
滚动窗口的整数大小。
- bias
如果为False,则计算会针对统计偏差进行校正。
示例
>>> pl.Series([1, 4, 2, 9]).rolling_skew(3) shape: (4,) Series: '' [f64] [ null null 0.381802 0.47033 ]
注意值是如何匹配的
>>> pl.Series([1, 4, 2]).skew(), pl.Series([4, 2, 9]).skew() (0.38180177416060584, 0.47033046033698594)
- rolling_std(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
- ddof: int = 1,
计算滚动标准差。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将被聚合为其标准差。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
- ddof
“自由度差值”:长度为N的窗口的除数是N - ddof
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0]) >>> s.rolling_std(window_size=3) shape: (6,) Series: 'a' [f64] [ null null 1.0 1.0 1.527525 2.0 ]
- rolling_sum(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
对此数组中的值应用滚动求和(移动求和)。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将被聚合为它们的总和。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.rolling_sum(window_size=2) shape: (5,) Series: 'a' [i64] [ null 3 5 7 9 ]
- rolling_var(
- window_size: int,
- weights: list[float] | None = None,
- *,
- min_periods: int | None = None,
- center: bool = False,
- ddof: int = 1,
计算滚动方差。
警告
此功能被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
一个长度为
window_size的窗口将遍历数组。填充此窗口的值将(可选地)与由weight向量给出的权重相乘。结果值将被聚合为其方差。给定行的窗口将包括该行本身及其前面的
window_size - 1个元素。- Parameters:
- window_size
窗口的长度以元素数量表示。
- weights
一个与窗口长度相同的可选切片,它将与窗口中的值进行元素级乘法。
- min_periods
在计算结果之前,窗口中应该为非空值的数量。如果设置为
None(默认值),它将被设置为等于window_size。- center
将标签设置在窗口的中心。
- ddof
“自由度差值”:长度为N的窗口的除数是N - ddof
示例
>>> s = pl.Series("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0]) >>> s.rolling_var(window_size=3) shape: (6,) Series: 'a' [f64] [ null null 1.0 1.0 2.333333 4.0 ]
- round(decimals: int = 0) Series[source]
将底层浮点数据四舍五入到
decimals位小数。- Parameters:
- decimals
四舍五入的小数位数。
示例
>>> s = pl.Series("a", [1.12345, 2.56789, 3.901234]) >>> s.round(2) shape: (3,) Series: 'a' [f64] [ 1.12 2.57 3.9 ]
- round_sig_figs(digits: int) Series[source]
四舍五入到指定的有效数字位数。
- Parameters:
- digits
要四舍五入的有效数字位数。
示例
>>> s = pl.Series([0.01234, 3.333, 3450.0]) >>> s.round_sig_figs(2) shape: (3,) Series: '' [f64] [ 0.012 3.3 3500.0 ]
- sample(
- n: int | None = None,
- *,
- fraction: float | None = None,
- with_replacement: bool = False,
- shuffle: bool = False,
- seed: int | None = None,
从这个系列中取样。
- Parameters:
- n
返回的项目数量。不能与
fraction一起使用。如果fraction为None,则默认为1。- fraction
返回项目的比例。不能与
n一起使用。- with_replacement
允许值被多次采样。
- shuffle
打乱采样数据点的顺序。
- seed
随机数生成器的种子。如果设置为None(默认值),则为每次采样操作生成一个随机种子。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.sample(2, seed=0) shape: (2,) Series: 'a' [i64] [ 1 5 ]
- scatter(
- indices: Series | Iterable[int] | int | np.ndarray[Any, Any],
- values: Series | Iterable[PythonLiteral] | PythonLiteral | None,
在索引位置设置值。
- Parameters:
- indices
表示索引位置的整数。
- values
替换值。
注释
使用此函数通常是一种反模式,因为它可能会阻止优化(谓词下推等)。考虑使用
pl.when(predicate).then(value).otherwise(self)代替。示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.scatter(1, 10) shape: (3,) Series: 'a' [i64] [ 1 10 3 ]
最好按如下方式实现:
>>> s.to_frame().with_row_index().select( ... pl.when(pl.col("index") == 1).then(10).otherwise(pl.col("a")) ... ) shape: (3, 1) ┌─────────┐ │ literal │ │ --- │ │ i64 │ ╞═════════╡ │ 1 │ │ 10 │ │ 3 │ └─────────┘
- search_sorted(
- element: IntoExpr | np.ndarray[Any, Any] | None,
- side: SearchSortedSide = 'any',
找到应插入元素以保持顺序的索引。
\[a[i-1] < v <= a[i]\]- Parameters:
- element
表达式或标量值。
- side{‘any’, ‘left’, ‘right’}
如果选择‘any’,则返回找到的第一个合适位置的索引。 如果选择‘left’,则返回找到的最左边合适位置的索引。 如果选择‘right’,则返回找到的最右边合适位置的索引。
示例
>>> s = pl.Series("set", [1, 2, 3, 4, 4, 5, 6, 7]) >>> s.search_sorted(4) 3 >>> s.search_sorted(4, "left") 3 >>> s.search_sorted(4, "right") 5 >>> s.search_sorted([1, 4, 5]) shape: (3,) Series: 'set' [u32] [ 0 3 5 ] >>> s.search_sorted([1, 4, 5], "left") shape: (3,) Series: 'set' [u32] [ 0 3 5 ] >>> s.search_sorted([1, 4, 5], "right") shape: (3,) Series: 'set' [u32] [ 1 5 6 ]
- set( ) Series[source]
设置掩码值。
- Parameters:
- filter
布尔掩码。
- value
用于替换被屏蔽值的值。
注释
使用此函数通常是一种反模式,因为它可能会阻止优化(谓词下推等)。考虑使用
pl.when(predicate).then(value).otherwise(self)代替。示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.set(s == 2, 10) shape: (3,) Series: 'a' [i64] [ 1 10 3 ]
最好按如下方式实现:
>>> s.to_frame().select( ... pl.when(pl.col("a") == 2).then(10).otherwise(pl.col("a")) ... ) shape: (3, 1) ┌─────────┐ │ literal │ │ --- │ │ i64 │ ╞═════════╡ │ 1 │ │ 10 │ │ 3 │ └─────────┘
- set_sorted(*, descending: bool = False) Self[source]
将Series标记为“已排序”。
使下游代码能够使用排序数组的快速路径。
- Parameters:
- descending
如果
Series的顺序是降序的。
警告
如果这个
Series没有排序,可能会导致错误的结果!! 请谨慎使用!示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.set_sorted().max() 3
- shift(n: int = 1, *, fill_value: IntoExpr | None = None) Series[source]
将值按给定的索引数进行移动。
- Parameters:
- n
向前移动的索引数量。如果传递了负值,则值将向相反方向移动。
- fill_value
用此值填充结果中的空值。接受表达式输入。 非表达式输入将被解析为字面量。
注释
此方法类似于SQL中的
LAG操作,当n的值为正时。当n的值为负时,它类似于LEAD。示例
默认情况下,值会向前移动一个索引。
>>> s = pl.Series([1, 2, 3, 4]) >>> s.shift() shape: (4,) Series: '' [i64] [ null 1 2 3 ]
传递一个负值以向相反方向移动。
>>> s.shift(-2) shape: (4,) Series: '' [i64] [ 3 4 null null ]
指定
fill_value以填充结果中的空值。>>> s.shift(-2, fill_value=100) shape: (4,) Series: '' [i64] [ 3 4 100 100 ]
- shrink_dtype() Series[source]
将数值列缩小到所需的最小数据类型。
缩小到适合此[
Series]极值所需的dtype。 这可以用于减少内存压力。示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5, 6]) >>> s shape: (6,) Series: 'a' [i64] [ 1 2 3 4 5 6 ] >>> s.shrink_dtype() shape: (6,) Series: 'a' [i8] [ 1 2 3 4 5 6 ]
- shrink_to_fit(*, in_place: bool = False) Series[source]
缩小系列内存使用。
缩小底层数组容量以完全适应实际数据。 (请注意,此函数不会更改Series数据类型)。
- shuffle(seed: int | None = None) Series[source]
打乱此系列的内容。
- Parameters:
- seed
随机数生成器的种子。如果设置为None(默认),每次调用shuffle时都会生成一个随机种子。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.shuffle(seed=1) shape: (3,) Series: 'a' [i64] [ 2 1 3 ]
- sign() Series[source]
计算数值类型的逐元素符号函数。
返回值计算如下:
如果 x 小于 0,则为 -1。
1 如果 x > 0。
x 否则(通常为 0,但如果输入为 NaN 则可能为 NaN)。
空值将按原样保留,并且输入的dtype也将保留。
示例
>>> s = pl.Series("a", [-9.0, -0.0, 0.0, 4.0, float("nan"), None]) >>> s.sign() shape: (6,) Series: 'a' [f64] [ -1.0 -0.0 0.0 1.0 NaN null ]
- sin() Series[source]
计算元素的正弦值。
示例
>>> import math >>> s = pl.Series("a", [0.0, math.pi / 2.0, math.pi]) >>> s.sin() shape: (3,) Series: 'a' [f64] [ 0.0 1.0 1.2246e-16 ]
- sinh() Series[source]
计算双曲正弦的逐元素值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.sinh() shape: (3,) Series: 'a' [f64] [ 1.175201 0.0 -1.175201 ]
- skew(*, bias: bool = True) float | None[source]
计算数据集的样本偏度。
对于正态分布的数据,偏度应该接近于零。对于单峰连续分布,偏度值大于零意味着分布的右侧尾部有更多的权重。函数
skewtest可以用来确定偏度值是否在统计上足够接近于零。有关更多信息,请参阅 scipy.stats。
- Parameters:
- biasbool, optional
如果为False,则计算会针对统计偏差进行校正。
注释
样本偏度计算为Fisher-Pearson偏度系数,即
\[g_1=\frac{m_3}{m_2^{3/2}}\]其中
\[m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i\]是偏置样本的第\(i\texttt{th}\)中心矩,而 \(\bar{x}\)是 样本均值。如果
bias为False,则计算会进行偏置校正,计算出的值是调整后的 Fisher-Pearson标准化矩系数,即\[G_1 = \frac{k_3}{k_2^{3/2}} = \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}\]示例
>>> s = pl.Series([1, 2, 2, 4, 5]) >>> s.skew() 0.34776706224699483
- slice(offset: int, length: int | None = None) Series[source]
获取此系列的一个切片。
- Parameters:
- offset
起始索引。支持负索引。
- length
切片的长度。如果设置为
None,将从偏移量开始选择所有行。
示例
>>> s = pl.Series("a", [1, 2, 3, 4]) >>> s.slice(1, 2) shape: (2,) Series: 'a' [i64] [ 2 3 ]
- sort(
- *,
- descending: bool = False,
- nulls_last: bool = False,
- multithreaded: bool = True,
- in_place: bool = False,
对这个系列进行排序。
- Parameters:
- descending
按降序排序。
- nulls_last
将空值放在最后而不是最前面。
- multithreaded
使用多线程进行排序。
- in_place
原地排序。
示例
>>> s = pl.Series("a", [1, 3, 4, 2]) >>> s.sort() shape: (4,) Series: 'a' [i64] [ 1 2 3 4 ] >>> s.sort(descending=True) shape: (4,) Series: 'a' [i64] [ 4 3 2 1 ]
- sqrt() Series[source]
计算元素的平方根。
语法糖用于
>>> pl.Series([1, 2]) ** 0.5 shape: (2,) Series: '' [f64] [ 1.0 1.414214 ]
示例
>>> s = pl.Series([1, 2, 3]) >>> s.sqrt() shape: (3,) Series: '' [f64] [ 1.0 1.414214 1.732051 ]
- std(ddof: int = 1) float | timedelta | None[source]
获取此系列的标准差。
- Parameters:
- ddof
“自由度差值”:计算中使用的除数是 N - ddof, 其中 N 表示元素的数量。 默认情况下,ddof 为 1。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.std() 1.0
- sum() int | float[source]
将此系列减少为总和值。
注释
{Int8, UInt8, Int16, UInt16} 中的数据类型在求和之前会被转换为 Int64,以防止溢出问题。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.sum() 6
- tail(n: int = 10) Series[source]
获取最后
n个元素。- Parameters:
- n
返回的元素数量。如果传递了负值,则返回除前
abs(n)个元素之外的所有元素。
示例
>>> s = pl.Series("a", [1, 2, 3, 4, 5]) >>> s.tail(3) shape: (3,) Series: 'a' [i64] [ 3 4 5 ]
传递一个负值以获取除前
abs(n)行之外的所有行。>>> s.tail(-3) shape: (2,) Series: 'a' [i64] [ 4 5 ]
- tan() Series[source]
计算元素的正切值。
示例
>>> import math >>> s = pl.Series("a", [0.0, math.pi / 2.0, math.pi]) >>> s.tan() shape: (3,) Series: 'a' [f64] [ 0.0 1.6331e16 -1.2246e-16 ]
- tanh() Series[source]
计算双曲正切的逐元素值。
示例
>>> s = pl.Series("a", [1.0, 0.0, -1.0]) >>> s.tanh() shape: (3,) Series: 'a' [f64] [ 0.761594 0.0 -0.761594 ]
- to_arrow(
- *,
- compat_level: CompatLevel | None = None,
返回底层的Arrow数组。
如果Series只包含一个块,此操作是零拷贝的。
- Parameters:
- compat_level
在导出Polars的内部数据结构时使用特定的兼容性级别。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s = s.to_arrow() >>> s <pyarrow.lib.Int64Array object at ...> [ 1, 2, 3 ]
- to_dummies(*, separator: str = '_', drop_first: bool = False) DataFrame[source]
获取虚拟/指示变量。
- Parameters:
- separator
生成列名时使用的分隔符/定界符。
- drop_first
从正在编码的变量中移除第一个类别。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.to_dummies() shape: (3, 3) ┌─────┬─────┬─────┐ │ a_1 ┆ a_2 ┆ a_3 │ │ --- ┆ --- ┆ --- │ │ u8 ┆ u8 ┆ u8 │ ╞═════╪═════╪═════╡ │ 1 ┆ 0 ┆ 0 │ │ 0 ┆ 1 ┆ 0 │ │ 0 ┆ 0 ┆ 1 │ └─────┴─────┴─────┘
>>> s.to_dummies(drop_first=True) shape: (3, 2) ┌─────┬─────┐ │ a_2 ┆ a_3 │ │ --- ┆ --- │ │ u8 ┆ u8 │ ╞═════╪═════╡ │ 0 ┆ 0 │ │ 1 ┆ 0 │ │ 0 ┆ 1 │ └─────┴─────┘
- to_frame(name: str | None = None) DataFrame[source]
将此系列转换为DataFrame。
- Parameters:
- name
可选地在新DataFrame中命名/重命名Series列。
示例
>>> s = pl.Series("a", [123, 456]) >>> df = s.to_frame() >>> df shape: (2, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 123 │ │ 456 │ └─────┘
>>> df = s.to_frame("xyz") >>> df shape: (2, 1) ┌─────┐ │ xyz │ │ --- │ │ i64 │ ╞═════╡ │ 123 │ │ 456 │ └─────┘
- to_init_repr(n: int = 1000) str[source]
将系列转换为可实例化的字符串表示。
- Parameters:
- n
仅使用前n个元素。
示例
>>> s = pl.Series("a", [1, 2, None, 4], dtype=pl.Int16) >>> print(s.to_init_repr()) pl.Series('a', [1, 2, None, 4], dtype=pl.Int16) >>> s_from_str_repr = eval(s.to_init_repr()) >>> s_from_str_repr shape: (4,) Series: 'a' [i16] [ 1 2 null 4 ]
- to_jax(device: jax.Device | str | None = None) jax.Array[source]
将此系列转换为Jax数组。
在版本0.20.27中添加。
警告
此功能目前被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
- Parameters:
- device
指定将在其上创建数组的jax
Device;可以提供字符串(如“cpu”、“gpu”或“tpu”),在这种情况下,设备将作为jax.devices(string)[0]检索。为了更具体的控制,您可以直接提供实例化的Device。如果为None,则数组将在默认设备上创建。
示例
>>> s = pl.Series("x", [10.5, 0.0, -10.0, 5.5]) >>> s.to_jax() Array([ 10.5, 0. , -10. , 5.5], dtype=float32)
- to_list() list[Any][source]
将此系列转换为Python列表。
此操作复制数据。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.to_list() [1, 2, 3] >>> type(s.to_list()) <class 'list'>
- to_numpy(
- *,
- writable: bool = False,
- allow_copy: bool = True,
- use_pyarrow: bool | None = None,
- zero_copy_only: bool | None = None,
将此系列转换为NumPy ndarray。
此操作仅在必要时复制数据。当满足以下所有条件时,转换是零拷贝:
数据类型是整数、浮点数、
Datetime、Duration或Array。该系列不包含空值。
该系列由单个块组成。
writable参数设置为False(默认值)。
- Parameters:
- writable
确保生成的数组是可写的。如果数组是在没有复制的情况下创建的,这将强制复制数据,因为底层的Arrow数据是不可变的。
- allow_copy
允许复制内存以执行转换。如果设置为
False,会导致非零拷贝的转换失败。- use_pyarrow
首先转换为PyArrow,然后调用pyarrow.Array.to_numpy转换为NumPy。如果设置为
False,则使用Polars自己的转换逻辑。自版本0.20.28起已弃用:Polars现在默认使用其本地引擎进行转换为NumPy。 要使用PyArrow的引擎,请调用
.to_arrow().to_numpy()代替。- zero_copy_only
如果转换为NumPy需要复制底层数据,则引发异常。例如,当Series包含空值或非数值类型时,会发生数据复制。
自版本0.20.10起已弃用:请改用
allow_copy参数,它是此参数的相反。
示例
没有空值的数值数据可以在不复制数据的情况下进行转换。 生成的数组将不可写。
>>> s = pl.Series([1, 2, 3], dtype=pl.Int8) >>> arr = s.to_numpy() >>> arr array([1, 2, 3], dtype=int8) >>> arr.flags.writeable False
设置
writable=True以强制复制数据使数组可写。>>> s.to_numpy(writable=True).flags.writeable True
包含空值的整数序列将被转换为浮点类型,其中
nan表示空值。这需要复制数据。>>> s = pl.Series([1, 2, None], dtype=pl.UInt16) >>> s.to_numpy() array([ 1., 2., nan], dtype=float32)
设置
allow_copy=False以在数据将被复制时引发错误。>>> s.to_numpy(allow_copy=False) Traceback (most recent call last): ... RuntimeError: copy not allowed: cannot convert to a NumPy array without copying data
数据类型为
Array和Struct的系列将导致一个多维数组。>>> s = pl.Series([[1, 2, 3], [4, 5, 6]], dtype=pl.Array(pl.Int64, 3)) >>> s.to_numpy() array([[1, 2, 3], [4, 5, 6]])
- to_pandas(
- *,
- use_pyarrow_extension_array: bool = False,
- **kwargs: Any,
将此系列转换为pandas系列。
如果未启用
use_pyarrow_extension_array,此操作将复制数据。- Parameters:
- use_pyarrow_extension_array
使用PyArrow支持的扩展数组代替NumPy数组作为pandas Series。这允许零拷贝操作并保留空值。如果PyArrow计算函数不支持后续操作,则对生成的pandas Series的操作可能会触发转换为NumPy。
- **kwargs
额外的关键字参数传递给
pyarrow.Array.to_pandas().
- Returns:
注释
此操作要求同时安装
pandas和pyarrow。示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.to_pandas() 0 1 1 2 2 3 Name: a, dtype: int64
空值被转换为
NaN。>>> s = pl.Series("b", [1, 2, None]) >>> s.to_pandas() 0 1.0 1 2.0 2 NaN Name: b, dtype: float64
传递
use_pyarrow_extension_array=True以获得由 PyArrow 扩展数组支持的 pandas Series。这将保留空值。>>> s.to_pandas(use_pyarrow_extension_array=True) 0 1 1 2 2 <NA> Name: b, dtype: int64[pyarrow]
- to_physical() Series[source]
将逻辑数据类型转换为物理表示。
List(inner)->List(physical of inner)Array(inner)->Array(physical of inner)Struct(fields)->Struct(physical of fields)其他数据类型将保持不变。
警告
物理表示是一个实现细节,并不保证是稳定的。
示例
复制pandas的 pd.Series.factorize 方法。
>>> s = pl.Series("values", ["a", None, "x", "a"]) >>> s.cast(pl.Categorical).to_physical() shape: (4,) Series: 'values' [u32] [ 0 null 1 0 ]
- to_torch() torch.Tensor[source]
将此系列转换为PyTorch张量。
在版本0.20.23中添加。
警告
此功能目前被视为不稳定。它可能会在任何时候更改,而不被视为破坏性更改。
注释
PyTorch 张量不支持 UInt16、UInt32 或 UInt64;这些数据类型将分别自动转换为 Int32、Int64 和 Int64。
示例
>>> s = pl.Series("x", [1, 0, 1, 2, 0], dtype=pl.UInt8) >>> s.to_torch() tensor([1, 0, 1, 2, 0], dtype=torch.uint8) >>> s = pl.Series("x", [5.5, -10.0, 2.5], dtype=pl.Float32) >>> s.to_torch() tensor([ 5.5000, -10.0000, 2.5000])
- top_k(k: int = 5) Series[source]
返回
k个最大的元素。非空元素总是优先于空元素。输出不保证按任何特定顺序排列,如果您希望输出排序,请在此函数后调用
sort()。这具有时间复杂度:
\[O(n)\]- Parameters:
- k
返回的元素数量。
另请参阅
示例
>>> s = pl.Series("a", [2, 5, 1, 4, 3]) >>> s.top_k(3) shape: (3,) Series: 'a' [i64] [ 5 4 3 ]
- unique(*, maintain_order: bool = False) Series[source]
获取系列中的唯一元素。
- Parameters:
- maintain_order
保持数据顺序。这需要更多的工作。
示例
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.unique().sort() shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
- unique_counts() Series[source]
返回按出现顺序排列的唯一值的计数。
示例
>>> s = pl.Series("id", ["a", "b", "b", "c", "c", "c"]) >>> s.unique_counts() shape: (3,) Series: 'id' [u32] [ 1 2 3 ]
- upper_bound() Self[source]
返回此Series数据类型的上限作为一个单位Series。
另请参阅
lower_bound返回给定Series数据类型的下限。
示例
>>> s = pl.Series("s", [-1, 0, 1], dtype=pl.Int8) >>> s.upper_bound() shape: (1,) Series: 's' [i8] [ 127 ]
>>> s = pl.Series("s", [1.0, 2.5, 3.0], dtype=pl.Float64) >>> s.upper_bound() shape: (1,) Series: 's' [f64] [ inf ]
- value_counts( ) DataFrame[source]
计算唯一值的出现次数。
- Parameters:
- sort
按计数降序排序输出。 如果设置为
False(默认值),输出的顺序是随机的。- parallel
并行执行计算。
注意
在分组上下文中,此选项可能不应启用,因为计算已经按组并行化。
- name
给结果计数列一个特定的名称; 如果
normalize为True,则默认为“proportion”, 否则默认为“count”。- normalize
如果为真,则给出唯一值的相对频率
- Returns:
- DataFrame
唯一值到其计数的映射。
示例
>>> s = pl.Series("color", ["red", "blue", "red", "green", "blue", "blue"]) >>> s.value_counts() shape: (3, 2) ┌───────┬───────┐ │ color ┆ count │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═══════╪═══════╡ │ red ┆ 2 │ │ green ┆ 1 │ │ blue ┆ 3 │ └───────┴───────┘
按计数排序输出并自定义计数列名称。
>>> s.value_counts(sort=True, name="n") shape: (3, 2) ┌───────┬─────┐ │ color ┆ n │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═══════╪═════╡ │ blue ┆ 3 │ │ red ┆ 2 │ │ green ┆ 1 │ └───────┴─────┘
- var(ddof: int = 1) float | timedelta | None[source]
获取此系列数据的方差。
- Parameters:
- ddof
“自由度差值”:计算中使用的除数是 N - ddof, 其中 N 表示元素的数量。 默认情况下,ddof 为 1。
示例
>>> s = pl.Series("a", [1, 2, 3]) >>> s.var() 1.0
- zip_with(mask: Series, other: Series) Self[source]
根据给定的掩码从自身或其他中取值。
当mask评估为真时,从self中取值。当mask评估为假时,从other中取值。
- Parameters:
- mask
布尔系列。
- other
相同类型的系列。
- Returns:
- Series
示例
>>> s1 = pl.Series([1, 2, 3, 4, 5]) >>> s2 = pl.Series([5, 4, 3, 2, 1]) >>> s1.zip_with(s1 < s2, s2) shape: (5,) Series: '' [i64] [ 1 2 3 2 1 ] >>> mask = pl.Series([True, False, True, False, True]) >>> s1.zip_with(mask, s2) shape: (5,) Series: '' [i64] [ 1 4 3 2 5 ]