6
6
"""
7
7
from __future__ import annotations
8
8
9
- from collections import abc
10
9
from typing import (
11
10
TYPE_CHECKING ,
12
11
Any ,
@@ -501,6 +500,16 @@ def sanitize_array(
501
500
if dtype is None :
502
501
dtype = data .dtype
503
502
data = lib .item_from_zerodim (data )
503
+ elif isinstance (data , range ):
504
+ # GH#16804
505
+ data = np .arange (data .start , data .stop , data .step , dtype = "int64" )
506
+ copy = False
507
+
508
+ if not is_list_like (data ):
509
+ if index is None :
510
+ raise ValueError ("index must be specified when data is not list-like" )
511
+ data = construct_1d_arraylike_from_scalar (data , len (index ), dtype )
512
+ return data
504
513
505
514
# GH#846
506
515
if isinstance (data , np .ndarray ):
@@ -525,14 +534,16 @@ def sanitize_array(
525
534
subarr = subarr .copy ()
526
535
return subarr
527
536
528
- elif isinstance (data , (list , tuple , abc .Set , abc .ValuesView )) and len (data ) > 0 :
529
- # TODO: deque, array.array
537
+ else :
530
538
if isinstance (data , (set , frozenset )):
531
539
# Raise only for unordered sets, e.g., not for dict_keys
532
540
raise TypeError (f"'{ type (data ).__name__ } ' type is unordered" )
541
+
542
+ # materialize e.g. generators, convert e.g. tuples, abc.ValueView
543
+ # TODO: non-standard array-likes we can convert to ndarray more efficiently?
533
544
data = list (data )
534
545
535
- if dtype is not None :
546
+ if dtype is not None or len ( data ) == 0 :
536
547
subarr = _try_cast (data , dtype , copy , raise_cast_failure )
537
548
else :
538
549
subarr = maybe_convert_platform (data )
@@ -541,22 +552,6 @@ def sanitize_array(
541
552
# "ExtensionArray")
542
553
subarr = maybe_cast_to_datetime (subarr , dtype ) # type: ignore[assignment]
543
554
544
- elif isinstance (data , range ):
545
- # GH#16804
546
- arr = np .arange (data .start , data .stop , data .step , dtype = "int64" )
547
- subarr = _try_cast (arr , dtype , copy , raise_cast_failure )
548
-
549
- elif not is_list_like (data ):
550
- if index is None :
551
- raise ValueError ("index must be specified when data is not list-like" )
552
- subarr = construct_1d_arraylike_from_scalar (data , len (index ), dtype )
553
-
554
- else :
555
- # realize e.g. generators
556
- # TODO: non-standard array-likes we can convert to ndarray more efficiently?
557
- data = list (data )
558
- subarr = _try_cast (data , dtype , copy , raise_cast_failure )
559
-
560
555
subarr = _sanitize_ndim (subarr , data , dtype , index )
561
556
562
557
if not (
0 commit comments