construction.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. """
  2. Constructor functions intended to be shared by pd.array, Series.__init__,
  3. and Index.__new__.
  4. These should not depend on core.internals.
  5. """
  6. from __future__ import annotations
  7. from typing import (
  8. TYPE_CHECKING,
  9. Optional,
  10. Sequence,
  11. Union,
  12. cast,
  13. overload,
  14. )
  15. import numpy as np
  16. from numpy import ma
  17. from pandas._libs import lib
  18. from pandas._libs.tslibs.period import Period
  19. from pandas._typing import (
  20. AnyArrayLike,
  21. ArrayLike,
  22. Dtype,
  23. DtypeObj,
  24. T,
  25. )
  26. from pandas.core.dtypes.base import (
  27. ExtensionDtype,
  28. _registry as registry,
  29. )
  30. from pandas.core.dtypes.cast import (
  31. construct_1d_arraylike_from_scalar,
  32. construct_1d_object_array_from_listlike,
  33. maybe_cast_to_datetime,
  34. maybe_cast_to_integer_array,
  35. maybe_convert_platform,
  36. maybe_infer_to_datetimelike,
  37. maybe_promote,
  38. )
  39. from pandas.core.dtypes.common import (
  40. is_datetime64_ns_dtype,
  41. is_dtype_equal,
  42. is_extension_array_dtype,
  43. is_integer_dtype,
  44. is_list_like,
  45. is_object_dtype,
  46. is_timedelta64_ns_dtype,
  47. )
  48. from pandas.core.dtypes.dtypes import PandasDtype
  49. from pandas.core.dtypes.generic import (
  50. ABCDataFrame,
  51. ABCExtensionArray,
  52. ABCIndex,
  53. ABCPandasArray,
  54. ABCRangeIndex,
  55. ABCSeries,
  56. )
  57. from pandas.core.dtypes.missing import isna
  58. import pandas.core.common as com
  59. if TYPE_CHECKING:
  60. from pandas import (
  61. Index,
  62. Series,
  63. )
  64. from pandas.core.arrays.base import ExtensionArray
  65. def array(
  66. data: Sequence[object] | AnyArrayLike,
  67. dtype: Dtype | None = None,
  68. copy: bool = True,
  69. ) -> ExtensionArray:
  70. """
  71. Create an array.
  72. Parameters
  73. ----------
  74. data : Sequence of objects
  75. The scalars inside `data` should be instances of the
  76. scalar type for `dtype`. It's expected that `data`
  77. represents a 1-dimensional array of data.
  78. When `data` is an Index or Series, the underlying array
  79. will be extracted from `data`.
  80. dtype : str, np.dtype, or ExtensionDtype, optional
  81. The dtype to use for the array. This may be a NumPy
  82. dtype or an extension type registered with pandas using
  83. :meth:`pandas.api.extensions.register_extension_dtype`.
  84. If not specified, there are two possibilities:
  85. 1. When `data` is a :class:`Series`, :class:`Index`, or
  86. :class:`ExtensionArray`, the `dtype` will be taken
  87. from the data.
  88. 2. Otherwise, pandas will attempt to infer the `dtype`
  89. from the data.
  90. Note that when `data` is a NumPy array, ``data.dtype`` is
  91. *not* used for inferring the array type. This is because
  92. NumPy cannot represent all the types of data that can be
  93. held in extension arrays.
  94. Currently, pandas will infer an extension dtype for sequences of
  95. ============================== =======================================
  96. Scalar Type Array Type
  97. ============================== =======================================
  98. :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray`
  99. :class:`pandas.Period` :class:`pandas.arrays.PeriodArray`
  100. :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray`
  101. :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray`
  102. :class:`int` :class:`pandas.arrays.IntegerArray`
  103. :class:`float` :class:`pandas.arrays.FloatingArray`
  104. :class:`str` :class:`pandas.arrays.StringArray` or
  105. :class:`pandas.arrays.ArrowStringArray`
  106. :class:`bool` :class:`pandas.arrays.BooleanArray`
  107. ============================== =======================================
  108. The ExtensionArray created when the scalar type is :class:`str` is determined by
  109. ``pd.options.mode.string_storage`` if the dtype is not explicitly given.
  110. For all other cases, NumPy's usual inference rules will be used.
  111. .. versionchanged:: 1.2.0
  112. Pandas now also infers nullable-floating dtype for float-like
  113. input data
  114. copy : bool, default True
  115. Whether to copy the data, even if not necessary. Depending
  116. on the type of `data`, creating the new array may require
  117. copying data, even if ``copy=False``.
  118. Returns
  119. -------
  120. ExtensionArray
  121. The newly created array.
  122. Raises
  123. ------
  124. ValueError
  125. When `data` is not 1-dimensional.
  126. See Also
  127. --------
  128. numpy.array : Construct a NumPy array.
  129. Series : Construct a pandas Series.
  130. Index : Construct a pandas Index.
  131. arrays.PandasArray : ExtensionArray wrapping a NumPy array.
  132. Series.array : Extract the array stored within a Series.
  133. Notes
  134. -----
  135. Omitting the `dtype` argument means pandas will attempt to infer the
  136. best array type from the values in the data. As new array types are
  137. added by pandas and 3rd party libraries, the "best" array type may
  138. change. We recommend specifying `dtype` to ensure that
  139. 1. the correct array type for the data is returned
  140. 2. the returned array type doesn't change as new extension types
  141. are added by pandas and third-party libraries
  142. Additionally, if the underlying memory representation of the returned
  143. array matters, we recommend specifying the `dtype` as a concrete object
  144. rather than a string alias or allowing it to be inferred. For example,
  145. a future version of pandas or a 3rd-party library may include a
  146. dedicated ExtensionArray for string data. In this event, the following
  147. would no longer return a :class:`arrays.PandasArray` backed by a NumPy
  148. array.
  149. >>> pd.array(['a', 'b'], dtype=str)
  150. <PandasArray>
  151. ['a', 'b']
  152. Length: 2, dtype: str32
  153. This would instead return the new ExtensionArray dedicated for string
  154. data. If you really need the new array to be backed by a NumPy array,
  155. specify that in the dtype.
  156. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1"))
  157. <PandasArray>
  158. ['a', 'b']
  159. Length: 2, dtype: str32
  160. Finally, Pandas has arrays that mostly overlap with NumPy
  161. * :class:`arrays.DatetimeArray`
  162. * :class:`arrays.TimedeltaArray`
  163. When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is
  164. passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray``
  165. rather than a ``PandasArray``. This is for symmetry with the case of
  166. timezone-aware data, which NumPy does not natively support.
  167. >>> pd.array(['2015', '2016'], dtype='datetime64[ns]')
  168. <DatetimeArray>
  169. ['2015-01-01 00:00:00', '2016-01-01 00:00:00']
  170. Length: 2, dtype: datetime64[ns]
  171. >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]')
  172. <TimedeltaArray>
  173. ['0 days 01:00:00', '0 days 02:00:00']
  174. Length: 2, dtype: timedelta64[ns]
  175. Examples
  176. --------
  177. If a dtype is not specified, pandas will infer the best dtype from the values.
  178. See the description of `dtype` for the types pandas infers for.
  179. >>> pd.array([1, 2])
  180. <IntegerArray>
  181. [1, 2]
  182. Length: 2, dtype: Int64
  183. >>> pd.array([1, 2, np.nan])
  184. <IntegerArray>
  185. [1, 2, <NA>]
  186. Length: 3, dtype: Int64
  187. >>> pd.array([1.1, 2.2])
  188. <FloatingArray>
  189. [1.1, 2.2]
  190. Length: 2, dtype: Float64
  191. >>> pd.array(["a", None, "c"])
  192. <StringArray>
  193. ['a', <NA>, 'c']
  194. Length: 3, dtype: string
  195. >>> with pd.option_context("string_storage", "pyarrow"):
  196. ... arr = pd.array(["a", None, "c"])
  197. ...
  198. >>> arr
  199. <ArrowStringArray>
  200. ['a', <NA>, 'c']
  201. Length: 3, dtype: string
  202. >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")])
  203. <PeriodArray>
  204. ['2000-01-01', '2000-01-01']
  205. Length: 2, dtype: period[D]
  206. You can use the string alias for `dtype`
  207. >>> pd.array(['a', 'b', 'a'], dtype='category')
  208. ['a', 'b', 'a']
  209. Categories (2, object): ['a', 'b']
  210. Or specify the actual dtype
  211. >>> pd.array(['a', 'b', 'a'],
  212. ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True))
  213. ['a', 'b', 'a']
  214. Categories (3, object): ['a' < 'b' < 'c']
  215. If pandas does not infer a dedicated extension type a
  216. :class:`arrays.PandasArray` is returned.
  217. >>> pd.array([1 + 1j, 3 + 2j])
  218. <PandasArray>
  219. [(1+1j), (3+2j)]
  220. Length: 2, dtype: complex128
  221. As mentioned in the "Notes" section, new extension types may be added
  222. in the future (by pandas or 3rd party libraries), causing the return
  223. value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype`
  224. as a NumPy dtype if you need to ensure there's no future change in
  225. behavior.
  226. >>> pd.array([1, 2], dtype=np.dtype("int32"))
  227. <PandasArray>
  228. [1, 2]
  229. Length: 2, dtype: int32
  230. `data` must be 1-dimensional. A ValueError is raised when the input
  231. has the wrong dimensionality.
  232. >>> pd.array(1)
  233. Traceback (most recent call last):
  234. ...
  235. ValueError: Cannot pass scalar '1' to 'pandas.array'.
  236. """
  237. from pandas.core.arrays import (
  238. BooleanArray,
  239. DatetimeArray,
  240. ExtensionArray,
  241. FloatingArray,
  242. IntegerArray,
  243. IntervalArray,
  244. PandasArray,
  245. PeriodArray,
  246. TimedeltaArray,
  247. )
  248. from pandas.core.arrays.string_ import StringDtype
  249. if lib.is_scalar(data):
  250. msg = f"Cannot pass scalar '{data}' to 'pandas.array'."
  251. raise ValueError(msg)
  252. elif isinstance(data, ABCDataFrame):
  253. raise TypeError("Cannot pass DataFrame to 'pandas.array'")
  254. if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ExtensionArray)):
  255. # Note: we exclude np.ndarray here, will do type inference on it
  256. dtype = data.dtype
  257. data = extract_array(data, extract_numpy=True)
  258. # this returns None for not-found dtypes.
  259. if isinstance(dtype, str):
  260. dtype = registry.find(dtype) or dtype
  261. if isinstance(data, ExtensionArray) and (
  262. dtype is None or is_dtype_equal(dtype, data.dtype)
  263. ):
  264. # e.g. TimedeltaArray[s], avoid casting to PandasArray
  265. if copy:
  266. return data.copy()
  267. return data
  268. if is_extension_array_dtype(dtype):
  269. cls = cast(ExtensionDtype, dtype).construct_array_type()
  270. return cls._from_sequence(data, dtype=dtype, copy=copy)
  271. if dtype is None:
  272. inferred_dtype = lib.infer_dtype(data, skipna=True)
  273. if inferred_dtype == "period":
  274. period_data = cast(Union[Sequence[Optional[Period]], AnyArrayLike], data)
  275. return PeriodArray._from_sequence(period_data, copy=copy)
  276. elif inferred_dtype == "interval":
  277. return IntervalArray(data, copy=copy)
  278. elif inferred_dtype.startswith("datetime"):
  279. # datetime, datetime64
  280. try:
  281. return DatetimeArray._from_sequence(data, copy=copy)
  282. except ValueError:
  283. # Mixture of timezones, fall back to PandasArray
  284. pass
  285. elif inferred_dtype.startswith("timedelta"):
  286. # timedelta, timedelta64
  287. return TimedeltaArray._from_sequence(data, copy=copy)
  288. elif inferred_dtype == "string":
  289. # StringArray/ArrowStringArray depending on pd.options.mode.string_storage
  290. return StringDtype().construct_array_type()._from_sequence(data, copy=copy)
  291. elif inferred_dtype == "integer":
  292. return IntegerArray._from_sequence(data, copy=copy)
  293. elif (
  294. inferred_dtype in ("floating", "mixed-integer-float")
  295. and getattr(data, "dtype", None) != np.float16
  296. ):
  297. # GH#44715 Exclude np.float16 bc FloatingArray does not support it;
  298. # we will fall back to PandasArray.
  299. return FloatingArray._from_sequence(data, copy=copy)
  300. elif inferred_dtype == "boolean":
  301. return BooleanArray._from_sequence(data, copy=copy)
  302. # Pandas overrides NumPy for
  303. # 1. datetime64[ns]
  304. # 2. timedelta64[ns]
  305. # so that a DatetimeArray is returned.
  306. if is_datetime64_ns_dtype(dtype):
  307. return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy)
  308. elif is_timedelta64_ns_dtype(dtype):
  309. return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy)
  310. return PandasArray._from_sequence(data, dtype=dtype, copy=copy)
  311. @overload
  312. def extract_array(
  313. obj: Series | Index, extract_numpy: bool = ..., extract_range: bool = ...
  314. ) -> ArrayLike:
  315. ...
  316. @overload
  317. def extract_array(
  318. obj: T, extract_numpy: bool = ..., extract_range: bool = ...
  319. ) -> T | ArrayLike:
  320. ...
  321. def extract_array(
  322. obj: T, extract_numpy: bool = False, extract_range: bool = False
  323. ) -> T | ArrayLike:
  324. """
  325. Extract the ndarray or ExtensionArray from a Series or Index.
  326. For all other types, `obj` is just returned as is.
  327. Parameters
  328. ----------
  329. obj : object
  330. For Series / Index, the underlying ExtensionArray is unboxed.
  331. extract_numpy : bool, default False
  332. Whether to extract the ndarray from a PandasArray.
  333. extract_range : bool, default False
  334. If we have a RangeIndex, return range._values if True
  335. (which is a materialized integer ndarray), otherwise return unchanged.
  336. Returns
  337. -------
  338. arr : object
  339. Examples
  340. --------
  341. >>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))
  342. ['a', 'b', 'c']
  343. Categories (3, object): ['a', 'b', 'c']
  344. Other objects like lists, arrays, and DataFrames are just passed through.
  345. >>> extract_array([1, 2, 3])
  346. [1, 2, 3]
  347. For an ndarray-backed Series / Index the ndarray is returned.
  348. >>> extract_array(pd.Series([1, 2, 3]))
  349. array([1, 2, 3])
  350. To extract all the way down to the ndarray, pass ``extract_numpy=True``.
  351. >>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)
  352. array([1, 2, 3])
  353. """
  354. if isinstance(obj, (ABCIndex, ABCSeries)):
  355. if isinstance(obj, ABCRangeIndex):
  356. if extract_range:
  357. return obj._values
  358. # https://github.com/python/mypy/issues/1081
  359. # error: Incompatible return value type (got "RangeIndex", expected
  360. # "Union[T, Union[ExtensionArray, ndarray[Any, Any]]]")
  361. return obj # type: ignore[return-value]
  362. return obj._values
  363. elif extract_numpy and isinstance(obj, ABCPandasArray):
  364. return obj.to_numpy()
  365. return obj
  366. def ensure_wrapped_if_datetimelike(arr):
  367. """
  368. Wrap datetime64 and timedelta64 ndarrays in DatetimeArray/TimedeltaArray.
  369. """
  370. if isinstance(arr, np.ndarray):
  371. if arr.dtype.kind == "M":
  372. from pandas.core.arrays import DatetimeArray
  373. return DatetimeArray._from_sequence(arr)
  374. elif arr.dtype.kind == "m":
  375. from pandas.core.arrays import TimedeltaArray
  376. return TimedeltaArray._from_sequence(arr)
  377. return arr
  378. def sanitize_masked_array(data: ma.MaskedArray) -> np.ndarray:
  379. """
  380. Convert numpy MaskedArray to ensure mask is softened.
  381. """
  382. mask = ma.getmaskarray(data)
  383. if mask.any():
  384. dtype, fill_value = maybe_promote(data.dtype, np.nan)
  385. dtype = cast(np.dtype, dtype)
  386. # Incompatible types in assignment (expression has type "ndarray[Any,
  387. # dtype[Any]]", variable has type "MaskedArray[Any, Any]")
  388. data = data.astype(dtype, copy=True) # type: ignore[assignment]
  389. data.soften_mask() # set hardmask False if it was True
  390. data[mask] = fill_value
  391. else:
  392. data = data.copy()
  393. return data
  394. def sanitize_array(
  395. data,
  396. index: Index | None,
  397. dtype: DtypeObj | None = None,
  398. copy: bool = False,
  399. *,
  400. allow_2d: bool = False,
  401. ) -> ArrayLike:
  402. """
  403. Sanitize input data to an ndarray or ExtensionArray, copy if specified,
  404. coerce to the dtype if specified.
  405. Parameters
  406. ----------
  407. data : Any
  408. index : Index or None, default None
  409. dtype : np.dtype, ExtensionDtype, or None, default None
  410. copy : bool, default False
  411. allow_2d : bool, default False
  412. If False, raise if we have a 2D Arraylike.
  413. Returns
  414. -------
  415. np.ndarray or ExtensionArray
  416. """
  417. if isinstance(data, ma.MaskedArray):
  418. data = sanitize_masked_array(data)
  419. if isinstance(dtype, PandasDtype):
  420. # Avoid ending up with a PandasArray
  421. dtype = dtype.numpy_dtype
  422. # extract ndarray or ExtensionArray, ensure we have no PandasArray
  423. data = extract_array(data, extract_numpy=True, extract_range=True)
  424. if isinstance(data, np.ndarray) and data.ndim == 0:
  425. if dtype is None:
  426. dtype = data.dtype
  427. data = lib.item_from_zerodim(data)
  428. elif isinstance(data, range):
  429. # GH#16804
  430. data = range_to_ndarray(data)
  431. copy = False
  432. if not is_list_like(data):
  433. if index is None:
  434. raise ValueError("index must be specified when data is not list-like")
  435. data = construct_1d_arraylike_from_scalar(data, len(index), dtype)
  436. return data
  437. elif isinstance(data, ABCExtensionArray):
  438. # it is already ensured above this is not a PandasArray
  439. # Until GH#49309 is fixed this check needs to come before the
  440. # ExtensionDtype check
  441. if dtype is not None:
  442. subarr = data.astype(dtype, copy=copy)
  443. elif copy:
  444. subarr = data.copy()
  445. else:
  446. subarr = data
  447. elif isinstance(dtype, ExtensionDtype):
  448. # create an extension array from its dtype
  449. _sanitize_non_ordered(data)
  450. cls = dtype.construct_array_type()
  451. subarr = cls._from_sequence(data, dtype=dtype, copy=copy)
  452. # GH#846
  453. elif isinstance(data, np.ndarray):
  454. if isinstance(data, np.matrix):
  455. data = data.A
  456. if dtype is None:
  457. subarr = data
  458. if data.dtype == object:
  459. subarr = maybe_infer_to_datetimelike(data)
  460. if subarr is data and copy:
  461. subarr = subarr.copy()
  462. else:
  463. # we will try to copy by-definition here
  464. subarr = _try_cast(data, dtype, copy)
  465. elif hasattr(data, "__array__"):
  466. # e.g. dask array GH#38645
  467. data = np.array(data, copy=copy)
  468. return sanitize_array(
  469. data,
  470. index=index,
  471. dtype=dtype,
  472. copy=False,
  473. allow_2d=allow_2d,
  474. )
  475. else:
  476. _sanitize_non_ordered(data)
  477. # materialize e.g. generators, convert e.g. tuples, abc.ValueView
  478. data = list(data)
  479. if len(data) == 0 and dtype is None:
  480. # We default to float64, matching numpy
  481. subarr = np.array([], dtype=np.float64)
  482. elif dtype is not None:
  483. subarr = _try_cast(data, dtype, copy)
  484. else:
  485. subarr = maybe_convert_platform(data)
  486. if subarr.dtype == object:
  487. subarr = cast(np.ndarray, subarr)
  488. subarr = maybe_infer_to_datetimelike(subarr)
  489. subarr = _sanitize_ndim(subarr, data, dtype, index, allow_2d=allow_2d)
  490. if isinstance(subarr, np.ndarray):
  491. # at this point we should have dtype be None or subarr.dtype == dtype
  492. dtype = cast(np.dtype, dtype)
  493. subarr = _sanitize_str_dtypes(subarr, data, dtype, copy)
  494. return subarr
  495. def range_to_ndarray(rng: range) -> np.ndarray:
  496. """
  497. Cast a range object to ndarray.
  498. """
  499. # GH#30171 perf avoid realizing range as a list in np.array
  500. try:
  501. arr = np.arange(rng.start, rng.stop, rng.step, dtype="int64")
  502. except OverflowError:
  503. # GH#30173 handling for ranges that overflow int64
  504. if (rng.start >= 0 and rng.step > 0) or (rng.step < 0 <= rng.stop):
  505. try:
  506. arr = np.arange(rng.start, rng.stop, rng.step, dtype="uint64")
  507. except OverflowError:
  508. arr = construct_1d_object_array_from_listlike(list(rng))
  509. else:
  510. arr = construct_1d_object_array_from_listlike(list(rng))
  511. return arr
  512. def _sanitize_non_ordered(data) -> None:
  513. """
  514. Raise only for unordered sets, e.g., not for dict_keys
  515. """
  516. if isinstance(data, (set, frozenset)):
  517. raise TypeError(f"'{type(data).__name__}' type is unordered")
  518. def _sanitize_ndim(
  519. result: ArrayLike,
  520. data,
  521. dtype: DtypeObj | None,
  522. index: Index | None,
  523. *,
  524. allow_2d: bool = False,
  525. ) -> ArrayLike:
  526. """
  527. Ensure we have a 1-dimensional result array.
  528. """
  529. if getattr(result, "ndim", 0) == 0:
  530. raise ValueError("result should be arraylike with ndim > 0")
  531. if result.ndim == 1:
  532. # the result that we want
  533. result = _maybe_repeat(result, index)
  534. elif result.ndim > 1:
  535. if isinstance(data, np.ndarray):
  536. if allow_2d:
  537. return result
  538. raise ValueError(
  539. f"Data must be 1-dimensional, got ndarray of shape {data.shape} instead"
  540. )
  541. if is_object_dtype(dtype) and isinstance(dtype, ExtensionDtype):
  542. # i.e. PandasDtype("O")
  543. result = com.asarray_tuplesafe(data, dtype=np.dtype("object"))
  544. cls = dtype.construct_array_type()
  545. result = cls._from_sequence(result, dtype=dtype)
  546. else:
  547. # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type
  548. # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[str,
  549. # dtype[Any], None]"
  550. result = com.asarray_tuplesafe(data, dtype=dtype) # type: ignore[arg-type]
  551. return result
  552. def _sanitize_str_dtypes(
  553. result: np.ndarray, data, dtype: np.dtype | None, copy: bool
  554. ) -> np.ndarray:
  555. """
  556. Ensure we have a dtype that is supported by pandas.
  557. """
  558. # This is to prevent mixed-type Series getting all casted to
  559. # NumPy string type, e.g. NaN --> '-1#IND'.
  560. if issubclass(result.dtype.type, str):
  561. # GH#16605
  562. # If not empty convert the data to dtype
  563. # GH#19853: If data is a scalar, result has already the result
  564. if not lib.is_scalar(data):
  565. if not np.all(isna(data)):
  566. data = np.array(data, dtype=dtype, copy=False)
  567. result = np.array(data, dtype=object, copy=copy)
  568. return result
  569. def _maybe_repeat(arr: ArrayLike, index: Index | None) -> ArrayLike:
  570. """
  571. If we have a length-1 array and an index describing how long we expect
  572. the result to be, repeat the array.
  573. """
  574. if index is not None:
  575. if 1 == len(arr) != len(index):
  576. arr = arr.repeat(len(index))
  577. return arr
  578. def _try_cast(
  579. arr: list | np.ndarray,
  580. dtype: np.dtype,
  581. copy: bool,
  582. ) -> ArrayLike:
  583. """
  584. Convert input to numpy ndarray and optionally cast to a given dtype.
  585. Parameters
  586. ----------
  587. arr : ndarray or list
  588. Excludes: ExtensionArray, Series, Index.
  589. dtype : np.dtype
  590. copy : bool
  591. If False, don't copy the data if not needed.
  592. Returns
  593. -------
  594. np.ndarray or ExtensionArray
  595. """
  596. is_ndarray = isinstance(arr, np.ndarray)
  597. if is_object_dtype(dtype):
  598. if not is_ndarray:
  599. subarr = construct_1d_object_array_from_listlike(arr)
  600. return subarr
  601. return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy)
  602. elif dtype.kind == "U":
  603. # TODO: test cases with arr.dtype.kind in ["m", "M"]
  604. if is_ndarray:
  605. arr = cast(np.ndarray, arr)
  606. shape = arr.shape
  607. if arr.ndim > 1:
  608. arr = arr.ravel()
  609. else:
  610. shape = (len(arr),)
  611. return lib.ensure_string_array(arr, convert_na_value=False, copy=copy).reshape(
  612. shape
  613. )
  614. elif dtype.kind in ["m", "M"]:
  615. return maybe_cast_to_datetime(arr, dtype)
  616. # GH#15832: Check if we are requesting a numeric dtype and
  617. # that we can convert the data to the requested dtype.
  618. elif is_integer_dtype(dtype):
  619. # this will raise if we have e.g. floats
  620. subarr = maybe_cast_to_integer_array(arr, dtype)
  621. else:
  622. subarr = np.array(arr, dtype=dtype, copy=copy)
  623. return subarr