MCPcopy
hub / github.com/pandas-dev/pandas / _try_cast

Function _try_cast

pandas/core/construction.py:791–852  ·  view source on GitHub ↗

Convert input to numpy ndarray and optionally cast to a given dtype. Parameters ---------- arr : ndarray or list Excludes: ExtensionArray, Series, Index. dtype : np.dtype copy : bool If False, don't copy the data if not needed. Returns ------- n

(
    arr: list | np.ndarray,
    dtype: np.dtype,
    copy: bool,
)

Source from the content-addressed store, hash-verified

789
790
791def _try_cast(
792 arr: list | np.ndarray,
793 dtype: np.dtype,
794 copy: bool,
795) -> ArrayLike:
796 """
797 Convert input to numpy ndarray and optionally cast to a given dtype.
798
799 Parameters
800 ----------
801 arr : ndarray or list
802 Excludes: ExtensionArray, Series, Index.
803 dtype : np.dtype
804 copy : bool
805 If False, don't copy the data if not needed.
806
807 Returns
808 -------
809 np.ndarray or ExtensionArray
810 """
811 is_ndarray = isinstance(arr, np.ndarray)
812
813 if dtype == object:
814 if not is_ndarray:
815 subarr = construct_1d_object_array_from_listlike(arr)
816 return subarr
817 return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy)
818
819 elif dtype.kind == "U":
820 # TODO: test cases with arr.dtype.kind in "mM"
821 if is_ndarray:
822 arr = cast(np.ndarray, arr)
823 shape = arr.shape
824 if arr.ndim > 1:
825 arr = arr.ravel()
826 else:
827 shape = (len(arr),)
828 return lib.ensure_string_array(arr, convert_na_value=False, copy=copy).reshape(
829 shape
830 )
831
832 elif dtype.kind in "mM":
833 if is_ndarray:
834 arr = cast(np.ndarray, arr)
835 if arr.ndim == 2 and arr.shape[1] == 1:
836 # GH#60081: DataFrame Constructor converts 1D data to array of
837 # shape (N, 1), but maybe_cast_to_datetime assumes 1D input
838 return maybe_cast_to_datetime(arr[:, 0], dtype).reshape(arr.shape)
839 return maybe_cast_to_datetime(arr, dtype)
840
841 # GH#15832: Check if we are requesting a numeric dtype and
842 # that we can convert the data to the requested dtype.
843 elif dtype.kind in "iu":
844 # this will raise if we have e.g. floats
845
846 subarr = maybe_cast_to_integer_array(arr, dtype)
847 elif not copy:
848 subarr = np.asarray(arr, dtype=dtype)

Callers 1

sanitize_arrayFunction · 0.85

Calls 8

maybe_cast_to_datetimeFunction · 0.90
astypeMethod · 0.45
ravelMethod · 0.45
reshapeMethod · 0.45
arrayMethod · 0.45

Tested by

no test coverage detected