跳到内容

astype

将数组复制到指定数据类型,而不考虑类型提升规则。

参数

名称 类型 描述 默认值
x

要转换的数组。

必需
dtype

期望的数据类型。

必需
copy

指定当指定的 dtype 与输入数组 x 的数据类型匹配时是否复制数组。如果为 True,则始终返回新分配的数组。如果为 False 且指定的 dtype 与输入数组的数据类型匹配,则返回输入数组;否则,返回新分配的数组。默认值:True

True
备注
  • 当将布尔输入数组转换为实数值数据类型时,True 会被转换为等于 1 的实数值,而 False 必须转换为等于 0 的实数值。

  • 当将布尔输入数组转换为复浮点数据类型时,True 会被转换为等于 1 + 0j 的复数,而 False 会被转换为等于 0 + 0j 的复数。

  • 当将实数值输入数组转换为 bool 类型时,值 0 会被转换为 False,非零值会转换为 True

  • 当将复浮点数组转换为 bool 类型时,值 0 + 0j 会被转换为 False,所有其他值都会转换为 True

返回值

名称 类型 描述
out 数组

一个具有指定数据类型的数组。返回的数组与 x 具有相同的形状。

示例

>>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
>>> o = sparse.astype(a, "float32")
>>> o.todense()
array([[0., 1.],
       [2., 0.]], dtype=float32)
源代码位于 sparse/numba_backend/_common.py
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
@_check_device
def astype(x, dtype, /, *, copy=True, device=None):
    """
    Copies an array to a specified data type irrespective of type-promotion rules.

    Parameters
    ----------
    x: array
        array to cast.
    dtype: dtype
        desired data type.
    copy: bool
        specifies whether to copy an array when the specified ``dtype`` matches the data type
        of the input array ``x``. If ``True``, a newly allocated array is always returned.
        If ``False`` and the specified ``dtype`` matches the data type of the input array,
        the input array is returned; otherwise, a newly allocated array is returned.
        Default: ``True``.

    Notes
    -----

       - When casting a boolean input array to a real-valued data type, a value of ``True`` is cast
         to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued
         number equal to ``0``.

       - When casting a boolean input array to a complex floating-point data type, a value of ``True``
       is cast to a complex number equal to ``1 + 0j``, and a value of ``False`` is cast to a complex
       number equal to ``0 + 0j``.

       - When casting a real-valued input array to ``bool``, a value of ``0`` is cast to ``False``,
       and a non-zero value is cast to ``True``.

       - When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` is cast
       to ``False``, and all other values are cast to ``True``.

    Returns
    -------
    out: array
        an array having the specified data type. The returned array has the same shape as ``x``.

    Examples
    --------
    >>> a = sparse.COO.from_numpy(np.array([[0, 1], [2, 0]]))
    >>> o = sparse.astype(a, "float32")
    >>> o.todense()  # doctest: +NORMALIZE_WHITESPACE
    array([[0., 1.],
           [2., 0.]], dtype=float32)
    """
    return x.astype(dtype, copy=copy)