def astype_nansafe(arr, dtype, copy=True, skipna=False):
<EOL>if is_extension_array_dtype(dtype):<EOL><INDENT>return dtype.construct_array_type()._from_sequence(<EOL>arr, dtype=dtype, copy=copy)<EOL><DEDENT>if not isinstance(dtype, np.dtype):<EOL><INDENT>dtype = pandas_dtype(dtype)<EOL><DEDENT>if issubclass(dtype.type, str):<EOL><INDENT>return lib.astype_str(arr.ravel(),<EOL>skipna=skipna).reshape(arr.shape)<EOL><DEDENT>elif is_datetime64_dtype(arr):<EOL><INDENT>if is_object_dtype(dtype):<EOL><INDENT>return tslib.ints_to_pydatetime(arr.view(np.int64))<EOL><DEDENT>elif dtype == np.int64:<EOL><INDENT>return arr.view(dtype)<EOL><DEDENT>if dtype.kind == '<STR_LIT:M>':<EOL><INDENT>return arr.astype(dtype)<EOL><DEDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>".format(from_dtype=arr.dtype,<EOL>to_dtype=dtype))<EOL><DEDENT>elif is_timedelta64_dtype(arr):<EOL><INDENT>if is_object_dtype(dtype):<EOL><INDENT>return tslibs.ints_to_pytimedelta(arr.view(np.int64))<EOL><DEDENT>elif dtype == np.int64:<EOL><INDENT>return arr.view(dtype)<EOL><DEDENT>if dtype not in [_INT64_DTYPE, _TD_DTYPE]:<EOL><INDENT>if dtype.kind == '<STR_LIT:m>':<EOL><INDENT>mask = isna(arr)<EOL>result = arr.astype(dtype).astype(np.float64)<EOL>result[mask] = np.nan<EOL>return result<EOL><DEDENT><DEDENT>elif dtype == _TD_DTYPE:<EOL><INDENT>return arr.astype(_TD_DTYPE, copy=copy)<EOL><DEDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>".format(from_dtype=arr.dtype,<EOL>to_dtype=dtype))<EOL><DEDENT>elif (np.issubdtype(arr.dtype, np.floating) and<EOL>np.issubdtype(dtype, np.integer)):<EOL><INDENT>if not np.isfinite(arr).all():<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>elif is_object_dtype(arr):<EOL><INDENT>if np.issubdtype(dtype.type, np.integer):<EOL><INDENT>return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)<EOL><DEDENT>elif is_datetime64_dtype(dtype):<EOL><INDENT>from pandas import to_datetime<EOL>return astype_nansafe(to_datetime(arr).values, dtype, copy=copy)<EOL><DEDENT>elif is_timedelta64_dtype(dtype):<EOL><INDENT>from pandas import to_timedelta<EOL>return astype_nansafe(to_timedelta(arr).values, dtype, copy=copy)<EOL><DEDENT><DEDENT>if dtype.name in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise ValueError(msg.format(dtype=dtype.name))<EOL><DEDENT>if copy or is_object_dtype(arr) or is_object_dtype(dtype):<EOL><INDENT>return arr.astype(dtype, copy=True)<EOL><DEDENT>return arr.view(dtype)<EOL>
Cast the elements of an array to a given dtype a nan-safe manner.

Parameters
----------
arr : ndarray
dtype : np.dtype
copy : bool, default True
    If False, a view will be attempted but may fail, if
    e.g. the item sizes don't align.
skipna: bool, default False
    Whether or not we should skip NaN when casting as a string-type.

Raises
------
ValueError
    The dtype was a datetime64/timedelta64 dtype, but it had no unit.