-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
/
Copy pathtest_subclass.py
450 lines (377 loc) · 16.7 KB
/
test_subclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
from pandas import DataFrame, Series, MultiIndex, Panel, Index
import pandas as pd
import pandas.util.testing as tm
from pandas.tests.frame.common import TestData
class TestDataFrameSubclassing(tm.TestCase, TestData):
def test_frame_subclassing_and_slicing(self):
# Subclass frame and ensure it returns the right class on slicing it
# In reference to PR 9632
class CustomSeries(Series):
@property
def _constructor(self):
return CustomSeries
def custom_series_function(self):
return 'OK'
class CustomDataFrame(DataFrame):
"""
Subclasses pandas DF, fills DF with simulation results, adds some
custom plotting functions.
"""
def __init__(self, *args, **kw):
super(CustomDataFrame, self).__init__(*args, **kw)
@property
def _constructor(self):
return CustomDataFrame
_constructor_sliced = CustomSeries
def custom_frame_function(self):
return 'OK'
data = {'col1': range(10),
'col2': range(10)}
cdf = CustomDataFrame(data)
# Did we get back our own DF class?
self.assertTrue(isinstance(cdf, CustomDataFrame))
# Do we get back our own Series class after selecting a column?
cdf_series = cdf.col1
self.assertTrue(isinstance(cdf_series, CustomSeries))
self.assertEqual(cdf_series.custom_series_function(), 'OK')
# Do we get back our own DF class after slicing row-wise?
cdf_rows = cdf[1:5]
self.assertTrue(isinstance(cdf_rows, CustomDataFrame))
self.assertEqual(cdf_rows.custom_frame_function(), 'OK')
# Make sure sliced part of multi-index frame is custom class
mcol = pd.MultiIndex.from_tuples([('A', 'A'), ('A', 'B')])
cdf_multi = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
self.assertTrue(isinstance(cdf_multi['A'], CustomDataFrame))
mcol = pd.MultiIndex.from_tuples([('A', ''), ('B', '')])
cdf_multi2 = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
self.assertTrue(isinstance(cdf_multi2['A'], CustomSeries))
def test_dataframe_metadata(self):
df = tm.SubclassedDataFrame({'X': [1, 2, 3], 'Y': [1, 2, 3]},
index=['a', 'b', 'c'])
df.testattr = 'XXX'
self.assertEqual(df.testattr, 'XXX')
self.assertEqual(df[['X']].testattr, 'XXX')
self.assertEqual(df.loc[['a', 'b'], :].testattr, 'XXX')
self.assertEqual(df.iloc[[0, 1], :].testattr, 'XXX')
# GH9776
self.assertEqual(df.iloc[0:1, :].testattr, 'XXX')
# GH10553
unpickled = self.round_trip_pickle(df)
tm.assert_frame_equal(df, unpickled)
self.assertEqual(df._metadata, unpickled._metadata)
self.assertEqual(df.testattr, unpickled.testattr)
def test_indexing_sliced(self):
# GH 11559
df = tm.SubclassedDataFrame({'X': [1, 2, 3],
'Y': [4, 5, 6],
'Z': [7, 8, 9]},
index=['a', 'b', 'c'])
res = df.loc[:, 'X']
exp = tm.SubclassedSeries([1, 2, 3], index=list('abc'), name='X')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
res = df.iloc[:, 1]
exp = tm.SubclassedSeries([4, 5, 6], index=list('abc'), name='Y')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
res = df.loc[:, 'Z']
exp = tm.SubclassedSeries([7, 8, 9], index=list('abc'), name='Z')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
res = df.loc['a', :]
exp = tm.SubclassedSeries([1, 4, 7], index=list('XYZ'), name='a')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
res = df.iloc[1, :]
exp = tm.SubclassedSeries([2, 5, 8], index=list('XYZ'), name='b')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
res = df.loc['c', :]
exp = tm.SubclassedSeries([3, 6, 9], index=list('XYZ'), name='c')
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
def test_subclass_stack(self):
<<<<<<< HEAD
# GH 15564
=======
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
df = tm.SubclassedDataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
index=['a', 'b', 'c'],
columns=['X', 'Y', 'Z'])
res = df.stack()
exp = tm.SubclassedSeries(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
index=[list('aaabbbccc'), list('XYZXYZXYZ')])
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
def test_subclass_stack_multi(self):
<<<<<<< HEAD
# GH 15564
=======
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
df = tm.SubclassedDataFrame([
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]],
index=MultiIndex.from_tuples(
<<<<<<< HEAD
list(zip(list('AABB'), list('cdcd'))),
names=['aaa', 'ccc']),
columns=MultiIndex.from_tuples(
list(zip(list('WWXX'), list('yzyz'))),
=======
zip(list('AABB'), list('cdcd')),
names=['aaa', 'ccc']),
columns=MultiIndex.from_tuples(
zip(list('WWXX'), list('yzyz')),
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
names=['www', 'yyy']))
exp = tm.SubclassedDataFrame([
[10, 12],
[11, 13],
[20, 22],
[21, 23],
[30, 32],
[31, 33],
[40, 42],
[41, 43]],
<<<<<<< HEAD
index=MultiIndex.from_tuples(list(zip(
list('AAAABBBB'), list('ccddccdd'), list('yzyzyzyz'))),
names=['aaa', 'ccc', 'yyy']),
columns=Index(['W', 'X'], name='www'))
=======
index=MultiIndex.from_tuples(
zip(list('AAAABBBB'), list('ccddccdd'), list('yzyzyzyz')),
names=['aaa', 'ccc', 'yyy']),
columns=MultiIndex.from_tuples(
zip(list('WX')), names=['www']))
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
res = df.stack()
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
res = df.stack('yyy')
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
exp = tm.SubclassedDataFrame([
[10, 11],
[12, 13],
[20, 21],
[22, 23],
[30, 31],
[32, 33],
[40, 41],
[42, 43]],
<<<<<<< HEAD
index=MultiIndex.from_tuples(list(zip(
list('AAAABBBB'), list('ccddccdd'), list('WXWXWXWX'))),
names=['aaa', 'ccc', 'www']),
columns=Index(['y', 'z'], name='yyy'))
=======
index=MultiIndex.from_tuples(
zip(list('AAAABBBB'), list('ccddccdd'), list('WXWXWXWX')),
names=['aaa', 'ccc', 'www']),
columns=MultiIndex.from_tuples(
zip(list('yz')), names=['yyy']))
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
res = df.stack('www')
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
def test_subclass_unstack(self):
<<<<<<< HEAD
# GH 15564
=======
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
df = tm.SubclassedDataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
index=['a', 'b', 'c'],
columns=['X', 'Y', 'Z'])
res = df.unstack()
exp = tm.SubclassedSeries(
[1, 4, 7, 2, 5, 8, 3, 6, 9],
index=[list('XXXYYYZZZ'), list('abcabcabc')])
tm.assert_series_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedSeries)
def test_subclass_unstack_multi(self):
<<<<<<< HEAD
# GH 15564
=======
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
df = tm.SubclassedDataFrame([
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]],
index=MultiIndex.from_tuples(
<<<<<<< HEAD
list(zip(list('AABB'), list('cdcd'))),
names=['aaa', 'ccc']),
columns=MultiIndex.from_tuples(
list(zip(list('WWXX'), list('yzyz'))),
=======
zip(list('AABB'), list('cdcd')),
names=['aaa', 'ccc']),
columns=MultiIndex.from_tuples(
zip(list('WWXX'), list('yzyz')),
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
names=['www', 'yyy']))
exp = tm.SubclassedDataFrame([
[10, 20, 11, 21, 12, 22, 13, 23],
[30, 40, 31, 41, 32, 42, 33, 43]],
<<<<<<< HEAD
index=Index(['A', 'B'], name='aaa'),
columns=MultiIndex.from_tuples(list(zip(
list('WWWWXXXX'), list('yyzzyyzz'), list('cdcdcdcd'))),
names=['www', 'yyy', 'ccc']))
=======
index=MultiIndex.from_tuples(
zip(list('AB')), names=['aaa']),
columns=MultiIndex.from_tuples(
zip(list('WWWWXXXX'), list('yyzzyyzz'), list('cdcdcdcd')),
names=['www', 'yyy', 'ccc']))
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
res = df.unstack()
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
res = df.unstack('ccc')
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
exp = tm.SubclassedDataFrame([
[10, 30, 11, 31, 12, 32, 13, 33],
[20, 40, 21, 41, 22, 42, 23, 43]],
<<<<<<< HEAD
index=Index(['c', 'd'], name='ccc'),
columns=MultiIndex.from_tuples(list(zip(
list('WWWWXXXX'), list('yyzzyyzz'), list('ABABABAB'))),
=======
index=MultiIndex.from_tuples(
zip(list('cd')), names=['ccc']),
columns=MultiIndex.from_tuples(
zip(list('WWWWXXXX'), list('yyzzyyzz'), list('ABABABAB')),
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
names=['www', 'yyy', 'aaa']))
res = df.unstack('aaa')
tm.assert_frame_equal(res, exp)
tm.assertIsInstance(res, tm.SubclassedDataFrame)
def test_subclass_pivot(self):
<<<<<<< HEAD
# GH 15564
=======
>>>>>>> bug fix; test stack, unstack, pivot for series and df with Index, MultiIndex
df = tm.SubclassedDataFrame({
'index': ['A', 'B', 'C', 'C', 'B', 'A'],
'columns': ['One', 'One', 'One', 'Two', 'Two', 'Two'],
'values': [1., 2., 3., 3., 2., 1.]})
pivoted = df.pivot(
index='index', columns='columns', values='values')
expected = tm.SubclassedDataFrame({
'One': {'A': 1., 'B': 2., 'C': 3.},
'Two': {'A': 1., 'B': 2., 'C': 3.}})
expected.index.name, expected.columns.name = 'index', 'columns'
tm.assert_frame_equal(pivoted, expected)
tm.assertIsInstance(pivoted, tm.SubclassedDataFrame)
def test_to_panel_expanddim(self):
# GH 9762
class SubclassedFrame(DataFrame):
@property
def _constructor_expanddim(self):
return SubclassedPanel
class SubclassedPanel(Panel):
pass
index = MultiIndex.from_tuples([(0, 0), (0, 1), (0, 2)])
df = SubclassedFrame({'X': [1, 2, 3], 'Y': [4, 5, 6]}, index=index)
result = df.to_panel()
self.assertTrue(isinstance(result, SubclassedPanel))
expected = SubclassedPanel([[[1, 2, 3]], [[4, 5, 6]]],
items=['X', 'Y'], major_axis=[0],
minor_axis=[0, 1, 2],
dtype='int64')
tm.assert_panel_equal(result, expected)
def test_subclass_attr_err_propagation(self):
# GH 11808
class A(DataFrame):
@property
def bar(self):
return self.i_dont_exist
with tm.assertRaisesRegexp(AttributeError, '.*i_dont_exist.*'):
A().bar
def test_subclass_align(self):
# GH 12983
df1 = tm.SubclassedDataFrame({'a': [1, 3, 5],
'b': [1, 3, 5]}, index=list('ACE'))
df2 = tm.SubclassedDataFrame({'c': [1, 2, 4],
'd': [1, 2, 4]}, index=list('ABD'))
res1, res2 = df1.align(df2, axis=0)
exp1 = tm.SubclassedDataFrame({'a': [1, np.nan, 3, np.nan, 5],
'b': [1, np.nan, 3, np.nan, 5]},
index=list('ABCDE'))
exp2 = tm.SubclassedDataFrame({'c': [1, 2, np.nan, 4, np.nan],
'd': [1, 2, np.nan, 4, np.nan]},
index=list('ABCDE'))
tm.assertIsInstance(res1, tm.SubclassedDataFrame)
tm.assert_frame_equal(res1, exp1)
tm.assertIsInstance(res2, tm.SubclassedDataFrame)
tm.assert_frame_equal(res2, exp2)
res1, res2 = df1.a.align(df2.c)
tm.assertIsInstance(res1, tm.SubclassedSeries)
tm.assert_series_equal(res1, exp1.a)
tm.assertIsInstance(res2, tm.SubclassedSeries)
tm.assert_series_equal(res2, exp2.c)
def test_subclass_align_combinations(self):
# GH 12983
df = tm.SubclassedDataFrame({'a': [1, 3, 5],
'b': [1, 3, 5]}, index=list('ACE'))
s = tm.SubclassedSeries([1, 2, 4], index=list('ABD'), name='x')
# frame + series
res1, res2 = df.align(s, axis=0)
exp1 = pd.DataFrame({'a': [1, np.nan, 3, np.nan, 5],
'b': [1, np.nan, 3, np.nan, 5]},
index=list('ABCDE'))
# name is lost when
exp2 = pd.Series([1, 2, np.nan, 4, np.nan],
index=list('ABCDE'), name='x')
tm.assertIsInstance(res1, tm.SubclassedDataFrame)
tm.assert_frame_equal(res1, exp1)
tm.assertIsInstance(res2, tm.SubclassedSeries)
tm.assert_series_equal(res2, exp2)
# series + frame
res1, res2 = s.align(df)
tm.assertIsInstance(res1, tm.SubclassedSeries)
tm.assert_series_equal(res1, exp2)
tm.assertIsInstance(res2, tm.SubclassedDataFrame)
tm.assert_frame_equal(res2, exp1)
def test_subclass_iterrows(self):
# GH 13977
df = tm.SubclassedDataFrame({'a': [1]})
for i, row in df.iterrows():
tm.assertIsInstance(row, tm.SubclassedSeries)
tm.assert_series_equal(row, df.loc[i])
def test_subclass_sparse_slice(self):
rows = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
ssdf = tm.SubclassedSparseDataFrame(rows)
ssdf.testattr = "testattr"
tm.assert_sp_frame_equal(ssdf.loc[:2],
tm.SubclassedSparseDataFrame(rows[:3]))
tm.assert_sp_frame_equal(ssdf.iloc[:2],
tm.SubclassedSparseDataFrame(rows[:2]))
tm.assert_sp_frame_equal(ssdf[:2],
tm.SubclassedSparseDataFrame(rows[:2]))
tm.assert_equal(ssdf.loc[:2].testattr, "testattr")
tm.assert_equal(ssdf.iloc[:2].testattr, "testattr")
tm.assert_equal(ssdf[:2].testattr, "testattr")
tm.assert_sp_series_equal(ssdf.loc[1],
tm.SubclassedSparseSeries(rows[1]),
check_names=False)
tm.assert_sp_series_equal(ssdf.iloc[1],
tm.SubclassedSparseSeries(rows[1]),
check_names=False)
def test_subclass_sparse_transpose(self):
ossdf = tm.SubclassedSparseDataFrame([[1, 2, 3],
[4, 5, 6]])
essdf = tm.SubclassedSparseDataFrame([[1, 4],
[2, 5],
[3, 6]])
tm.assert_sp_frame_equal(ossdf.T, essdf)