27
27
is_array_like ,
28
28
is_bool_dtype ,
29
29
is_datetime64_any_dtype ,
30
+ is_datetime64tz_dtype ,
30
31
is_dtype_equal ,
31
32
is_integer ,
32
33
is_object_dtype ,
42
43
from pandas .core .arrays .sparse .dtype import SparseDtype
43
44
from pandas .core .base import PandasObject
44
45
import pandas .core .common as com
45
- from pandas .core .construction import sanitize_array
46
+ from pandas .core .construction import extract_array , sanitize_array
46
47
from pandas .core .indexers import check_array_indexer
47
48
from pandas .core .missing import interpolate_2d
48
49
import pandas .core .ops as ops
@@ -312,7 +313,7 @@ def __init__(
312
313
dtype = dtype .subtype
313
314
314
315
if index is not None and not is_scalar (data ):
315
- raise Exception ("must only pass scalars with an index " )
316
+ raise Exception ("must only pass scalars with an index" )
316
317
317
318
if is_scalar (data ):
318
319
if index is not None :
@@ -367,6 +368,19 @@ def __init__(
367
368
sparse_index = data ._sparse_index
368
369
sparse_values = np .asarray (data .sp_values , dtype = dtype )
369
370
elif sparse_index is None :
371
+ data = extract_array (data , extract_numpy = True )
372
+ if not isinstance (data , np .ndarray ):
373
+ # EA
374
+ if is_datetime64tz_dtype (data .dtype ):
375
+ warnings .warn (
376
+ f"Creating SparseArray from { data .dtype } data "
377
+ "loses timezone information. Cast to object before "
378
+ "sparse to retain timezone information." ,
379
+ UserWarning ,
380
+ stacklevel = 2 ,
381
+ )
382
+ data = np .asarray (data , dtype = "datetime64[ns]" )
383
+ data = np .asarray (data )
370
384
sparse_values , sparse_index , fill_value = make_sparse (
371
385
data , kind = kind , fill_value = fill_value , dtype = dtype
372
386
)
@@ -1497,7 +1511,7 @@ def _formatter(self, boxed=False):
1497
1511
SparseArray ._add_unary_ops ()
1498
1512
1499
1513
1500
- def make_sparse (arr , kind = "block" , fill_value = None , dtype = None , copy = False ):
1514
+ def make_sparse (arr : np . ndarray , kind = "block" , fill_value = None , dtype = None , copy = False ):
1501
1515
"""
1502
1516
Convert ndarray to sparse format
1503
1517
@@ -1513,7 +1527,7 @@ def make_sparse(arr, kind="block", fill_value=None, dtype=None, copy=False):
1513
1527
-------
1514
1528
(sparse_values, index, fill_value) : (ndarray, SparseIndex, Scalar)
1515
1529
"""
1516
- arr = com . values_from_object (arr )
1530
+ assert isinstance (arr , np . ndarray )
1517
1531
1518
1532
if arr .ndim > 1 :
1519
1533
raise TypeError ("expected dimension <= 1 data" )
0 commit comments