Skip to content

Commit 1e4b4bd

Browse files
committed
handle generic list-like
1 parent 959ed4c commit 1e4b4bd

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

pandas/_libs/lib.pyx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,22 @@ def is_period(val: object) -> bool:
886886
return util.is_period_object(val)
887887

888888

889+
cpdef inline bint is_list_like(object obj):
890+
"""
891+
Parameters
892+
----------
893+
obj : object
894+
895+
Returns
896+
-------
897+
bool : if this is a list-like object
898+
"""
899+
return (hasattr(obj, '__iter__') and
900+
not isinstance(obj, (str, bytes))
901+
# exclude zero-dimensional numpy arrays, effectively scalars
902+
and not (isinstance(obj, ndarray) and obj.ndim == 0))
903+
904+
889905
_TYPE_MAP = {
890906
'categorical': 'categorical',
891907
'category': 'categorical',

pandas/_libs/reshape.pyx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ from cython import Py_ssize_t
44
from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
55
uint32_t, uint64_t, float32_t, float64_t, ndarray)
66
import numpy
7+
from pandas._libs.lib import is_list_like
78

89

910
ctypedef fused reshape_t:
@@ -120,7 +121,7 @@ def explode(ndarray[object] values):
120121
counts = numpy.zeros(n, dtype='uint8')
121122
for i in range(n):
122123
v = values[i]
123-
if isinstance(v, (list, tuple)):
124+
if is_list_like(v):
124125
if len(v):
125126
counts[i] += len(v)
126127
else:
@@ -134,7 +135,7 @@ def explode(ndarray[object] values):
134135
for i in range(n):
135136
v = values[i]
136137

137-
if isinstance(v, (list, tuple)):
138+
if is_list_like(v):
138139
if len(v):
139140
for j in range(len(v)):
140141
result[count] = v[j]

pandas/tests/series/test_explode.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ def test_basic():
1717

1818

1919
def test_mixed_type():
20-
s = pd.Series([[0, 1, 2], np.nan, None, [], ("a", "b")], name="foo")
20+
s = pd.Series(
21+
[[0, 1, 2], np.nan, None, np.array([]), pd.Series(["a", "b"])], name="foo"
22+
)
2123
result = s.explode()
2224
expected = pd.Series(
2325
[0, 1, 2, np.nan, None, np.nan, "a", "b"],

0 commit comments

Comments
 (0)