@@ -1129,10 +1129,10 @@ def test_isnotnull(self):
1129
1129
@pytest .mark .parametrize ('index' , [None , list ('ab' )]) # noqa: F811
1130
1130
@pytest .mark .parametrize ('columns' , [None , list ('cd' )])
1131
1131
@pytest .mark .parametrize ('fill_value' , [None , 0 , np .nan ])
1132
- @pytest .mark .parametrize ('dtype' , [object , bool , int , float , np .uint16 ])
1132
+ @pytest .mark .parametrize ('dtype' , [bool , int , float , np .uint16 ])
1133
1133
def test_from_to_scipy (spmatrix , index , columns , fill_value , dtype ):
1134
1134
# GH 4343
1135
- tm ._skip_if_no_scipy ( )
1135
+ tm .skip_if_no_package ( 'scipy' )
1136
1136
1137
1137
# Make one ndarray and from it one sparse matrix, both to be used for
1138
1138
# constructing frames and comparing results
@@ -1180,6 +1180,51 @@ def test_from_to_scipy(spmatrix, index, columns, fill_value, dtype):
1180
1180
tm .assert_equal (sdf .to_coo ().dtype , np .object_ )
1181
1181
1182
1182
1183
+ @pytest .mark .parametrize ('fill_value' , [None , 0 , np .nan ]) # noqa: F811
1184
+ def test_from_to_scipy_object (spmatrix , fill_value ):
1185
+ # GH 4343
1186
+ dtype = object
1187
+ columns = list ('cd' )
1188
+ index = list ('ab' )
1189
+ tm .skip_if_no_package ('scipy' , max_version = '0.19.0' )
1190
+
1191
+ # Make one ndarray and from it one sparse matrix, both to be used for
1192
+ # constructing frames and comparing results
1193
+ arr = np .eye (2 , dtype = dtype )
1194
+ try :
1195
+ spm = spmatrix (arr )
1196
+ assert spm .dtype == arr .dtype
1197
+ except (TypeError , AssertionError ):
1198
+ # If conversion to sparse fails for this spmatrix type and arr.dtype,
1199
+ # then the combination is not currently supported in NumPy, so we
1200
+ # can just skip testing it thoroughly
1201
+ return
1202
+
1203
+ sdf = pd .SparseDataFrame (spm , index = index , columns = columns ,
1204
+ default_fill_value = fill_value )
1205
+
1206
+ # Expected result construction is kind of tricky for all
1207
+ # dtype-fill_value combinations; easiest to cast to something generic
1208
+ # and except later on
1209
+ rarr = arr .astype (object )
1210
+ rarr [arr == 0 ] = np .nan
1211
+ expected = pd .SparseDataFrame (rarr , index = index , columns = columns ).fillna (
1212
+ fill_value if fill_value is not None else np .nan )
1213
+
1214
+ # Assert frame is as expected
1215
+ sdf_obj = sdf .astype (object )
1216
+ tm .assert_sp_frame_equal (sdf_obj , expected )
1217
+ tm .assert_frame_equal (sdf_obj .to_dense (), expected .to_dense ())
1218
+
1219
+ # Assert spmatrices equal
1220
+ tm .assert_equal (dict (sdf .to_coo ().todok ()), dict (spm .todok ()))
1221
+
1222
+ # Ensure dtype is preserved if possible
1223
+ res_dtype = object
1224
+ tm .assert_contains_all (sdf .dtypes , {np .dtype (res_dtype )})
1225
+ tm .assert_equal (sdf .to_coo ().dtype , res_dtype )
1226
+
1227
+
1183
1228
class TestSparseDataFrameArithmetic (tm .TestCase ):
1184
1229
1185
1230
def test_numeric_op_scalar (self ):
0 commit comments