|
| 1 | +from collections import abc |
1 | 2 | from decimal import Decimal
|
2 | 3 | from fractions import Fraction
|
3 | 4 | from numbers import Number
|
@@ -886,6 +887,60 @@ def is_period(val: object) -> bool:
|
886 | 887 | return util.is_period_object(val)
|
887 | 888 |
|
888 | 889 |
|
| 890 | +def is_list_like(obj: object, allow_sets: bool = True): |
| 891 | + """ |
| 892 | + Check if the object is list-like. |
| 893 | +
|
| 894 | + Objects that are considered list-like are for example Python |
| 895 | + lists, tuples, sets, NumPy arrays, and Pandas Series. |
| 896 | +
|
| 897 | + Strings and datetime objects, however, are not considered list-like. |
| 898 | +
|
| 899 | + Parameters |
| 900 | + ---------- |
| 901 | + obj : The object to check |
| 902 | + allow_sets : boolean, default True |
| 903 | + If this parameter is False, sets will not be considered list-like |
| 904 | +
|
| 905 | + .. versionadded:: 0.24.0 |
| 906 | +
|
| 907 | + Returns |
| 908 | + ------- |
| 909 | + is_list_like : bool |
| 910 | + Whether `obj` has list-like properties. |
| 911 | +
|
| 912 | + Examples |
| 913 | + -------- |
| 914 | + >>> is_list_like([1, 2, 3]) |
| 915 | + True |
| 916 | + >>> is_list_like({1, 2, 3}) |
| 917 | + True |
| 918 | + >>> is_list_like(datetime(2017, 1, 1)) |
| 919 | + False |
| 920 | + >>> is_list_like("foo") |
| 921 | + False |
| 922 | + >>> is_list_like(1) |
| 923 | + False |
| 924 | + >>> is_list_like(np.array([2])) |
| 925 | + True |
| 926 | + >>> is_list_like(np.array(2))) |
| 927 | + False |
| 928 | + """ |
| 929 | + return c_is_list_like(obj, allow_sets) |
| 930 | + |
| 931 | + |
| 932 | +cdef inline bint c_is_list_like(object obj, bint allow_sets): |
| 933 | + return ( |
| 934 | + isinstance(obj, abc.Iterable) |
| 935 | + # we do not count strings/unicode/bytes as list-like |
| 936 | + and not isinstance(obj, (str, bytes)) |
| 937 | + # exclude zero-dimensional numpy arrays, effectively scalars |
| 938 | + and not (util.is_array(obj) and obj.ndim == 0) |
| 939 | + # exclude sets if allow_sets is False |
| 940 | + and not (allow_sets is False and isinstance(obj, abc.Set)) |
| 941 | + ) |
| 942 | + |
| 943 | + |
889 | 944 | _TYPE_MAP = {
|
890 | 945 | 'categorical': 'categorical',
|
891 | 946 | 'category': 'categorical',
|
|
0 commit comments