Skip to content

Commit 8d41928

Browse files
BUG: add function to check whether data is all scalar in pandas.array
1 parent 4fd428f commit 8d41928

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

pandas/_libs/lib.pyi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ def maybe_indices_to_slice(
165165
indices: npt.NDArray[np.intp],
166166
max_len: int,
167167
) -> slice | npt.NDArray[np.intp]: ...
168+
def is_all_scalar(obj: list | tuple) -> bool: ...
168169
def is_all_arraylike(obj: list) -> bool: ...
169170

170171
# -----------------------------------------------------------------

pandas/_libs/lib.pyx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,26 @@ cpdef ndarray[object] ensure_string_array(
862862
return result
863863

864864

865+
@cython.wraparound(False)
866+
@cython.boundscheck(False)
867+
cpdef bool is_all_scalar(obj: list | tuple):
868+
# Optimized for lists and tuples
869+
cdef:
870+
Py_ssize_t i, n = len(obj)
871+
bool all_scalars = True
872+
object temp
873+
874+
for i in range(n):
875+
temp = obj[i]
876+
if isinstance(temp, (bytes, str)):
877+
continue
878+
elif hasattr(temp, "__iter__"):
879+
all_scalars = False
880+
break
881+
882+
return all_scalars
883+
884+
865885
def is_all_arraylike(obj: list) -> bool:
866886
"""
867887
Should we treat these as levels of a MultiIndex, as opposed to Index items?

pandas/core/construction.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,8 +322,8 @@ def array(
322322
return data
323323

324324
# to avoid returning an array of string representation of objects.
325-
if dtype == StringDtype():
326-
if any(not lib.is_scalar(i) for i in data):
325+
if isinstance(dtype, StringDtype) and isinstance(data, (list, tuple)):
326+
if not lib.is_all_scalar(data):
327327
raise TypeError("Values must be a 1D list-like")
328328

329329
if isinstance(dtype, ExtensionDtype):

0 commit comments

Comments
 (0)