Skip to content

Commit 4ef793f

Browse files
h-vetinarijreback
authored andcommitted
Fixturize tests/frame/test_constructors.py (#25635)
1 parent 6af5840 commit 4ef793f

File tree

1 file changed

+81
-69
lines changed

1 file changed

+81
-69
lines changed

pandas/tests/frame/test_constructors.py

+81-69
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,14 @@
1717
from pandas import (
1818
Categorical, DataFrame, Index, MultiIndex, RangeIndex, Series, Timedelta,
1919
Timestamp, date_range, isna)
20-
from pandas.tests.frame.common import TestData
2120
import pandas.util.testing as tm
2221

2322
MIXED_FLOAT_DTYPES = ['float16', 'float32', 'float64']
2423
MIXED_INT_DTYPES = ['uint8', 'uint16', 'uint32', 'uint64', 'int8', 'int16',
2524
'int32', 'int64']
2625

2726

28-
class TestDataFrameConstructors(TestData):
27+
class TestDataFrameConstructors:
2928

3029
@pytest.mark.parametrize('constructor', [
3130
lambda: DataFrame(),
@@ -60,14 +59,14 @@ def test_emptylike_constructor(
6059
result = DataFrame(emptylike)
6160
tm.assert_frame_equal(result, expected)
6261

63-
def test_constructor_mixed(self):
62+
def test_constructor_mixed(self, float_string_frame):
6463
index, data = tm.getMixedTypeDict()
6564

6665
# TODO(wesm), incomplete test?
6766
indexed_frame = DataFrame(data, index=index) # noqa
6867
unindexed_frame = DataFrame(data) # noqa
6968

70-
assert self.mixed_frame['foo'].dtype == np.object_
69+
assert float_string_frame['foo'].dtype == np.object_
7170

7271
def test_constructor_cast_failure(self):
7372
foo = DataFrame({'a': ['a', 'b', 'c']}, dtype=np.float64)
@@ -181,11 +180,11 @@ def test_constructor_dtype_str_na_values(self, string_dtype):
181180
df = DataFrame({'A': ['x', np.nan]}, dtype=string_dtype)
182181
assert np.isnan(df.iloc[1, 0])
183182

184-
def test_constructor_rec(self):
185-
rec = self.frame.to_records(index=False)
183+
def test_constructor_rec(self, float_frame):
184+
rec = float_frame.to_records(index=False)
186185
rec.dtype.names = list(rec.dtype.names)[::-1]
187186

188-
index = self.frame.index
187+
index = float_frame.index
189188

190189
df = DataFrame(rec)
191190
tm.assert_index_equal(df.columns, pd.Index(rec.dtype.names))
@@ -244,24 +243,29 @@ def test_constructor_ordereddict(self):
244243
assert expected == list(df.columns)
245244

246245
def test_constructor_dict(self):
247-
frame = DataFrame({'col1': self.ts1,
248-
'col2': self.ts2})
246+
datetime_series = tm.makeTimeSeries(nper=30)
247+
# test expects index shifted by 5
248+
datetime_series_short = tm.makeTimeSeries(nper=30)[5:]
249+
250+
frame = DataFrame({'col1': datetime_series,
251+
'col2': datetime_series_short})
249252

250253
# col2 is padded with NaN
251-
assert len(self.ts1) == 30
252-
assert len(self.ts2) == 25
254+
assert len(datetime_series) == 30
255+
assert len(datetime_series_short) == 25
253256

254-
tm.assert_series_equal(self.ts1, frame['col1'], check_names=False)
257+
tm.assert_series_equal(frame['col1'], datetime_series.rename('col1'))
255258

256-
exp = pd.Series(np.concatenate([[np.nan] * 5, self.ts2.values]),
257-
index=self.ts1.index, name='col2')
259+
exp = pd.Series(np.concatenate([[np.nan] * 5,
260+
datetime_series_short.values]),
261+
index=datetime_series.index, name='col2')
258262
tm.assert_series_equal(exp, frame['col2'])
259263

260-
frame = DataFrame({'col1': self.ts1,
261-
'col2': self.ts2},
264+
frame = DataFrame({'col1': datetime_series,
265+
'col2': datetime_series_short},
262266
columns=['col2', 'col3', 'col4'])
263267

264-
assert len(frame) == len(self.ts2)
268+
assert len(frame) == len(datetime_series_short)
265269
assert 'col1' not in frame
266270
assert isna(frame['col3']).all()
267271

@@ -361,18 +365,24 @@ def test_constructor_dict_nan_tuple_key(self, value):
361365

362366
@pytest.mark.skipif(not PY36, reason='Insertion order for Python>=3.6')
363367
def test_constructor_dict_order_insertion(self):
368+
datetime_series = tm.makeTimeSeries(nper=30)
369+
datetime_series_short = tm.makeTimeSeries(nper=25)
370+
364371
# GH19018
365372
# initialization ordering: by insertion order if python>= 3.6
366-
d = {'b': self.ts2, 'a': self.ts1}
373+
d = {'b': datetime_series_short, 'a': datetime_series}
367374
frame = DataFrame(data=d)
368375
expected = DataFrame(data=d, columns=list('ba'))
369376
tm.assert_frame_equal(frame, expected)
370377

371378
@pytest.mark.skipif(PY36, reason='order by value for Python<3.6')
372379
def test_constructor_dict_order_by_values(self):
380+
datetime_series = tm.makeTimeSeries(nper=30)
381+
datetime_series_short = tm.makeTimeSeries(nper=25)
382+
373383
# GH19018
374384
# initialization ordering: by value if python<3.6
375-
d = {'b': self.ts2, 'a': self.ts1}
385+
d = {'b': datetime_series_short, 'a': datetime_series}
376386
frame = DataFrame(data=d)
377387
expected = DataFrame(data=d, columns=list('ab'))
378388
tm.assert_frame_equal(frame, expected)
@@ -462,7 +472,7 @@ def test_constructor_with_embedded_frames(self):
462472
result = df2.loc[1, 0]
463473
tm.assert_frame_equal(result, df1 + 10)
464474

465-
def test_constructor_subclass_dict(self):
475+
def test_constructor_subclass_dict(self, float_frame):
466476
# Test for passing dict subclass to constructor
467477
data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in range(10)),
468478
'col2': tm.TestSubDict((x, 20.0 * x) for x in range(10))}
@@ -478,13 +488,13 @@ def test_constructor_subclass_dict(self):
478488
# try with defaultdict
479489
from collections import defaultdict
480490
data = {}
481-
self.frame['B'][:10] = np.nan
482-
for k, v in self.frame.items():
491+
float_frame['B'][:10] = np.nan
492+
for k, v in float_frame.items():
483493
dct = defaultdict(dict)
484494
dct.update(v.to_dict())
485495
data[k] = dct
486496
frame = DataFrame(data)
487-
tm.assert_frame_equal(self.frame.sort_index(), frame)
497+
tm.assert_frame_equal(float_frame.sort_index(), frame)
488498

489499
def test_constructor_dict_block(self):
490500
expected = np.array([[4., 3., 2., 1.]])
@@ -923,14 +933,14 @@ def test_constructor_arrays_and_scalars(self):
923933
with pytest.raises(ValueError, match='must pass an index'):
924934
DataFrame({'a': False, 'b': True})
925935

926-
def test_constructor_DataFrame(self):
927-
df = DataFrame(self.frame)
928-
tm.assert_frame_equal(df, self.frame)
936+
def test_constructor_DataFrame(self, float_frame):
937+
df = DataFrame(float_frame)
938+
tm.assert_frame_equal(df, float_frame)
929939

930-
df_casted = DataFrame(self.frame, dtype=np.int64)
940+
df_casted = DataFrame(float_frame, dtype=np.int64)
931941
assert df_casted.values.dtype == np.int64
932942

933-
def test_constructor_more(self):
943+
def test_constructor_more(self, float_frame):
934944
# used to be in test_matrix.py
935945
arr = np.random.randn(10)
936946
dm = DataFrame(arr, columns=['A'], index=np.arange(10))
@@ -956,8 +966,8 @@ def test_constructor_more(self):
956966
with pytest.raises(ValueError, match='cast'):
957967
DataFrame(mat, index=[0, 1], columns=[0], dtype=float)
958968

959-
dm = DataFrame(DataFrame(self.frame._series))
960-
tm.assert_frame_equal(dm, self.frame)
969+
dm = DataFrame(DataFrame(float_frame._series))
970+
tm.assert_frame_equal(dm, float_frame)
961971

962972
# int cast
963973
dm = DataFrame({'A': np.ones(10, dtype=int),
@@ -1223,8 +1233,9 @@ def test_constructor_scalar(self):
12231233
expected = DataFrame({"a": [0, 0, 0]}, index=idx)
12241234
tm.assert_frame_equal(df, expected, check_dtype=False)
12251235

1226-
def test_constructor_Series_copy_bug(self):
1227-
df = DataFrame(self.frame['A'], index=self.frame.index, columns=['A'])
1236+
def test_constructor_Series_copy_bug(self, float_frame):
1237+
df = DataFrame(float_frame['A'], index=float_frame.index,
1238+
columns=['A'])
12281239
df.copy()
12291240

12301241
def test_constructor_mixed_dict_and_Series(self):
@@ -1286,10 +1297,10 @@ def test_constructor_list_of_namedtuples(self):
12861297
result = DataFrame(tuples, columns=['y', 'z'])
12871298
tm.assert_frame_equal(result, expected)
12881299

1289-
def test_constructor_orient(self):
1290-
data_dict = self.mixed_frame.T._series
1300+
def test_constructor_orient(self, float_string_frame):
1301+
data_dict = float_string_frame.T._series
12911302
recons = DataFrame.from_dict(data_dict, orient='index')
1292-
expected = self.mixed_frame.sort_index()
1303+
expected = float_string_frame.sort_index()
12931304
tm.assert_frame_equal(recons, expected)
12941305

12951306
# dict of sequence
@@ -1393,38 +1404,38 @@ def test_constructor_Series_differently_indexed(self):
13931404
tm.assert_index_equal(df2.index, other_index)
13941405
tm.assert_frame_equal(df2, exp2)
13951406

1396-
def test_constructor_manager_resize(self):
1397-
index = list(self.frame.index[:5])
1398-
columns = list(self.frame.columns[:3])
1407+
def test_constructor_manager_resize(self, float_frame):
1408+
index = list(float_frame.index[:5])
1409+
columns = list(float_frame.columns[:3])
13991410

1400-
result = DataFrame(self.frame._data, index=index,
1411+
result = DataFrame(float_frame._data, index=index,
14011412
columns=columns)
14021413
tm.assert_index_equal(result.index, Index(index))
14031414
tm.assert_index_equal(result.columns, Index(columns))
14041415

1405-
def test_constructor_from_items(self):
1406-
items = [(c, self.frame[c]) for c in self.frame.columns]
1416+
def test_constructor_from_items(self, float_frame, float_string_frame):
1417+
items = [(c, float_frame[c]) for c in float_frame.columns]
14071418
with tm.assert_produces_warning(FutureWarning,
14081419
check_stacklevel=False):
14091420
recons = DataFrame.from_items(items)
1410-
tm.assert_frame_equal(recons, self.frame)
1421+
tm.assert_frame_equal(recons, float_frame)
14111422

14121423
# pass some columns
14131424
with tm.assert_produces_warning(FutureWarning,
14141425
check_stacklevel=False):
14151426
recons = DataFrame.from_items(items, columns=['C', 'B', 'A'])
1416-
tm.assert_frame_equal(recons, self.frame.loc[:, ['C', 'B', 'A']])
1427+
tm.assert_frame_equal(recons, float_frame.loc[:, ['C', 'B', 'A']])
14171428

14181429
# orient='index'
14191430

1420-
row_items = [(idx, self.mixed_frame.xs(idx))
1421-
for idx in self.mixed_frame.index]
1431+
row_items = [(idx, float_string_frame.xs(idx))
1432+
for idx in float_string_frame.index]
14221433
with tm.assert_produces_warning(FutureWarning,
14231434
check_stacklevel=False):
14241435
recons = DataFrame.from_items(row_items,
1425-
columns=self.mixed_frame.columns,
1436+
columns=float_string_frame.columns,
14261437
orient='index')
1427-
tm.assert_frame_equal(recons, self.mixed_frame)
1438+
tm.assert_frame_equal(recons, float_string_frame)
14281439
assert recons['A'].dtype == np.float64
14291440

14301441
msg = "Must pass columns with orient='index'"
@@ -1435,16 +1446,16 @@ def test_constructor_from_items(self):
14351446

14361447
# orient='index', but thar be tuples
14371448
arr = construct_1d_object_array_from_listlike(
1438-
[('bar', 'baz')] * len(self.mixed_frame))
1439-
self.mixed_frame['foo'] = arr
1440-
row_items = [(idx, list(self.mixed_frame.xs(idx)))
1441-
for idx in self.mixed_frame.index]
1449+
[('bar', 'baz')] * len(float_string_frame))
1450+
float_string_frame['foo'] = arr
1451+
row_items = [(idx, list(float_string_frame.xs(idx)))
1452+
for idx in float_string_frame.index]
14421453
with tm.assert_produces_warning(FutureWarning,
14431454
check_stacklevel=False):
14441455
recons = DataFrame.from_items(row_items,
1445-
columns=self.mixed_frame.columns,
1456+
columns=float_string_frame.columns,
14461457
orient='index')
1447-
tm.assert_frame_equal(recons, self.mixed_frame)
1458+
tm.assert_frame_equal(recons, float_string_frame)
14481459
assert isinstance(recons['foo'][0], tuple)
14491460

14501461
with tm.assert_produces_warning(FutureWarning,
@@ -1485,14 +1496,15 @@ def test_from_items_deprecation(self):
14851496
columns=['col1', 'col2', 'col3'],
14861497
orient='index')
14871498

1488-
def test_constructor_mix_series_nonseries(self):
1489-
df = DataFrame({'A': self.frame['A'],
1490-
'B': list(self.frame['B'])}, columns=['A', 'B'])
1491-
tm.assert_frame_equal(df, self.frame.loc[:, ['A', 'B']])
1499+
def test_constructor_mix_series_nonseries(self, float_frame):
1500+
df = DataFrame({'A': float_frame['A'],
1501+
'B': list(float_frame['B'])}, columns=['A', 'B'])
1502+
tm.assert_frame_equal(df, float_frame.loc[:, ['A', 'B']])
14921503

14931504
msg = 'does not match index length'
14941505
with pytest.raises(ValueError, match=msg):
1495-
DataFrame({'A': self.frame['A'], 'B': list(self.frame['B'])[:-2]})
1506+
DataFrame({'A': float_frame['A'],
1507+
'B': list(float_frame['B'])[:-2]})
14961508

14971509
def test_constructor_miscast_na_int_dtype(self):
14981510
df = DataFrame([[np.nan, 1], [1, 0]], dtype=np.int64)
@@ -1752,24 +1764,24 @@ def test_constructor_for_list_with_dtypes(self):
17521764
expected = expected.sort_index()
17531765
tm.assert_series_equal(result, expected)
17541766

1755-
def test_constructor_frame_copy(self):
1756-
cop = DataFrame(self.frame, copy=True)
1767+
def test_constructor_frame_copy(self, float_frame):
1768+
cop = DataFrame(float_frame, copy=True)
17571769
cop['A'] = 5
17581770
assert (cop['A'] == 5).all()
1759-
assert not (self.frame['A'] == 5).all()
1771+
assert not (float_frame['A'] == 5).all()
17601772

1761-
def test_constructor_ndarray_copy(self):
1762-
df = DataFrame(self.frame.values)
1773+
def test_constructor_ndarray_copy(self, float_frame):
1774+
df = DataFrame(float_frame.values)
17631775

1764-
self.frame.values[5] = 5
1776+
float_frame.values[5] = 5
17651777
assert (df.values[5] == 5).all()
17661778

1767-
df = DataFrame(self.frame.values, copy=True)
1768-
self.frame.values[6] = 6
1779+
df = DataFrame(float_frame.values, copy=True)
1780+
float_frame.values[6] = 6
17691781
assert not (df.values[6] == 6).all()
17701782

1771-
def test_constructor_series_copy(self):
1772-
series = self.frame._series
1783+
def test_constructor_series_copy(self, float_frame):
1784+
series = float_frame._series
17731785

17741786
df = DataFrame({'A': series['A']})
17751787
df['A'][:] = 5
@@ -2318,7 +2330,7 @@ class List(list):
23182330
tm.assert_frame_equal(result, expected)
23192331

23202332

2321-
class TestDataFrameConstructorWithDatetimeTZ(TestData):
2333+
class TestDataFrameConstructorWithDatetimeTZ:
23222334

23232335
def test_from_dict(self):
23242336

0 commit comments

Comments
 (0)