pandas.api.extensions.ExtensionArray.take#

ExtensionArray.take(indices, *, allow_fill=False, fill_value=None)[源代码]#

从数组中提取元素。

Parameters:
indices整数序列或一维整数 np.ndarray

将被提取的索引。

allow_fillbool,默认 False

如何处理 indices 中的负值。

  • False:indices 中的负值表示从右边开始的位置索引(默认)。这类似于 numpy.take()

  • True:indices 中的负值表示缺失值。这些值被设置为 fill_value。任何其他负值都会引发 ValueError

fill_value任意,可选

allow_fill 为 True 时,用于 NA 索引的填充值。这可以是 None,在这种情况下,将使用类型的默认 NA 值 self.dtype.na_value

对于许多 ExtensionArrays,fill_value 将有两种表示形式:面向用户的“装箱”标量,以及底层的物理 NA 值。fill_value 应该是面向用户的版本,并且实现应负责在必要时将其转换为物理版本以进行 take 操作。

Returns:
ExtensionArray
Raises:
IndexError

当索引超出数组范围时。

ValueError

indices 包含除 -1 以外的负值且 allow_fill 为 True 时。

参见

numpy.take

沿轴从数组中获取元素。

api.extensions.take

从数组中提取元素。

Notes

ExtensionArray.take 由 Series.__getitem__, .loc, ilocindices 是值序列时调用。此外,它还被 Series.reindex() 或任何其他导致重新对齐的方法(带有 fill_value)调用。

Examples

这是一个示例实现,它依赖于将扩展数组转换为对象 dtype。这使用了辅助方法 pandas.api.extensions.take()

def take(self, indices, allow_fill=False, fill_value=None):
    from pandas.core.algorithms import take

    # If the ExtensionArray is backed by an ndarray, then
    # just pass that here instead of coercing to object.
    data = self.astype(object)

    if allow_fill and fill_value is None:
        fill_value = self.dtype.na_value

    # fill value should always be translated from the scalar
    # type for the array, to the physical storage type for
    # the data, before passing to take.

    result = take(data, indices, fill_value=fill_value,
                  allow_fill=allow_fill)
    return self._from_sequence(result, dtype=self.dtype)