@@ -1164,6 +1164,37 @@ def test_loc_getitem_listlike_all_retains_sparse(self):
1164
1164
result = df .loc [[0 , 1 ]]
1165
1165
tm .assert_frame_equal (result , df )
1166
1166
1167
+ @td .skip_if_no_scipy
1168
+ def test_loc_getitem_sparse_frame (self ):
1169
+ # GH34687
1170
+ from scipy .sparse import eye
1171
+
1172
+ df = DataFrame .sparse .from_spmatrix (eye (5 ))
1173
+ result = df .loc [range (2 )]
1174
+ expected = DataFrame (
1175
+ [[1.0 , 0.0 , 0.0 , 0.0 , 0.0 ], [0.0 , 1.0 , 0.0 , 0.0 , 0.0 ]],
1176
+ dtype = SparseDtype ("float64" , 0.0 ),
1177
+ )
1178
+ tm .assert_frame_equal (result , expected )
1179
+
1180
+ result = df .loc [range (2 )].loc [range (1 )]
1181
+ expected = DataFrame (
1182
+ [[1.0 , 0.0 , 0.0 , 0.0 , 0.0 ]], dtype = SparseDtype ("float64" , 0.0 )
1183
+ )
1184
+ tm .assert_frame_equal (result , expected )
1185
+
1186
+ def test_loc_getitem_sparse_series (self ):
1187
+ # GH34687
1188
+ s = Series ([1.0 , 0.0 , 0.0 , 0.0 , 0.0 ], dtype = SparseDtype ("float64" , 0.0 ))
1189
+
1190
+ result = s .loc [range (2 )]
1191
+ expected = Series ([1.0 , 0.0 ], dtype = SparseDtype ("float64" , 0.0 ))
1192
+ tm .assert_series_equal (result , expected )
1193
+
1194
+ result = s .loc [range (3 )].loc [range (2 )]
1195
+ expected = Series ([1.0 , 0.0 ], dtype = SparseDtype ("float64" , 0.0 ))
1196
+ tm .assert_series_equal (result , expected )
1197
+
1167
1198
@pytest .mark .parametrize ("key_type" , [iter , np .array , Series , Index ])
1168
1199
def test_loc_getitem_iterable (self , float_frame , key_type ):
1169
1200
idx = key_type (["A" , "B" , "C" ])
0 commit comments