コード例 #1
0
def cast(pda: Union[pdarray, Strings],
         dt: Union[np.dtype, str]) -> Union[pdarray, Strings]:
    """
    Cast an array to another dtype.

    Parameters
    ----------
    pda : pdarray or Strings
        The array of values to cast
    dtype : np.dtype or str
        The target dtype to cast values to

    Returns
    -------
    pdarray or Strings
        Array of values cast to desired dtype

    Notes
    -----
    The cast is performed according to Chapel's casting rules and is NOT safe 
    from overflows or underflows. The user must ensure that the target dtype 
    has the precision and capacity to hold the desired result.
    
    Examples
    --------
    >>> ak.cast(ak.linspace(1.0,5.0,5), dt=ak.int64)
    array([1, 2, 3, 4, 5])    
    
    >>> ak.cast(ak.arange(0,5), dt=ak.float64).dtype
    dtype('float64')
    
    >>> ak.cast(ak.arange(0,5), dt=ak.bool)
    array([False, True, True, True, True])
    
    >>> ak.cast(ak.linspace(0,4,5), dt=ak.bool)
    array([False, True, True, True, True])
    """

    if isinstance(pda, pdarray):
        name = pda.name
        objtype = "pdarray"
    elif isinstance(pda, Strings):
        name = '+'.join((pda.offsets.name, pda.bytes.name))
        objtype = "str"
    # typechecked decorator guarantees no other case

    dt = _as_dtype(dt)
    opt = ""
    cmd = "cast"
    args = "{} {} {} {}".format(name, objtype, dt.name, opt)
    repMsg = generic_msg(cmd=cmd, args=args)
    if dt.name.startswith("str"):
        return Strings(*(type_cast(str, repMsg).split("+")))
    else:
        return create_pdarray(type_cast(str, repMsg))
コード例 #2
0
def cast(pda: Union[pdarray, Strings], dt) -> Union[pdarray, Strings]:
    """
    Cast an array to another dtype.

    Parameters
    ----------
    pda : pdarray or Strings
        The array of values to cast
    dtype : np.dtype or str
        The target dtype to cast values to

    Returns
    -------
    pdarray or Strings
        Array of values cast to desired dtype

    Notes
    -----
    The cast is performed according to Chapel's casting rules and is NOT safe 
    from overflows or underflows. The user must ensure that the target dtype 
    has the precision and capacity to hold the desired result.
    """

    if isinstance(pda, pdarray):
        name = pda.name
        objtype = "pdarray"
    elif isinstance(pda, Strings):
        name = '+'.join((pda.offsets.name, pda.bytes.name))
        objtype = "str"
    # typechecked decorator guarantees no other case

    dt = _as_dtype(dt)
    opt = ""
    msg = "cast {} {} {} {}".format(name, objtype, dt.name, opt)
    repMsg = generic_msg(msg)
    if dt.name.startswith("str"):
        return Strings(*(type_cast(str, repMsg).split("+")))
    else:
        return create_pdarray(type_cast(str, repMsg))