|
4 | 4 | Note: pandas.core.common is *not* part of the public API. |
5 | 5 | """ |
6 | 6 |
|
7 | | -import collections |
8 | | -from collections import abc |
| 7 | +from collections import abc, defaultdict |
9 | 8 | from datetime import datetime, timedelta |
10 | 9 | from functools import partial |
11 | 10 | import inspect |
12 | | -from typing import Any, Collection, Iterable, Union |
| 11 | +from typing import Any, Collection, Iterable, List, Union |
13 | 12 |
|
14 | 13 | import numpy as np |
15 | 14 |
|
16 | 15 | from pandas._libs import lib, tslibs |
17 | | -from pandas._typing import T |
| 16 | +from pandas._typing import AnyArrayLike, Scalar, T |
18 | 17 | from pandas.compat.numpy import _np_version_under1p17 |
19 | 18 |
|
20 | 19 | from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike |
|
24 | 23 | is_extension_array_dtype, |
25 | 24 | is_integer, |
26 | 25 | ) |
27 | | -from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries |
| 26 | +from pandas.core.dtypes.generic import ( |
| 27 | + ABCExtensionArray, |
| 28 | + ABCIndex, |
| 29 | + ABCIndexClass, |
| 30 | + ABCSeries, |
| 31 | +) |
28 | 32 | from pandas.core.dtypes.inference import _iterable_not_string |
29 | 33 | from pandas.core.dtypes.missing import isna, isnull, notnull # noqa |
30 | 34 |
|
@@ -367,12 +371,12 @@ def standardize_mapping(into): |
367 | 371 | Series.to_dict |
368 | 372 | """ |
369 | 373 | if not inspect.isclass(into): |
370 | | - if isinstance(into, collections.defaultdict): |
371 | | - return partial(collections.defaultdict, into.default_factory) |
| 374 | + if isinstance(into, defaultdict): |
| 375 | + return partial(defaultdict, into.default_factory) |
372 | 376 | into = type(into) |
373 | 377 | if not issubclass(into, abc.Mapping): |
374 | 378 | raise TypeError(f"unsupported type: {into}") |
375 | | - elif into == collections.defaultdict: |
| 379 | + elif into == defaultdict: |
376 | 380 | raise TypeError("to_dict() only accepts initialized defaultdicts") |
377 | 381 | return into |
378 | 382 |
|
@@ -473,3 +477,18 @@ def f(x): |
473 | 477 | f = mapper |
474 | 478 |
|
475 | 479 | return f |
| 480 | + |
| 481 | + |
| 482 | +def convert_to_list_like( |
| 483 | + values: Union[Scalar, Iterable, AnyArrayLike] |
| 484 | +) -> Union[List, AnyArrayLike]: |
| 485 | + """ |
| 486 | + Convert list-like or scalar input to list-like. List, numpy and pandas array-like |
| 487 | + inputs are returned unmodified whereas others are converted to list. |
| 488 | + """ |
| 489 | + if isinstance(values, (list, np.ndarray, ABCIndex, ABCSeries, ABCExtensionArray)): |
| 490 | + return values |
| 491 | + elif isinstance(values, abc.Iterable) and not isinstance(values, str): |
| 492 | + return list(values) |
| 493 | + |
| 494 | + return [values] |
0 commit comments