Skip to content

Commit a887988

Browse files
committed
Addresses GH #21918
removed test_operations.py fixed syntax for python 2.7 fix comments from commit
1 parent 2f2876b commit a887988

File tree

8 files changed

+595
-620
lines changed

8 files changed

+595
-620
lines changed

pandas/tests/indexes/multi/test_analytics.py

+429
Large diffs are not rendered by default.
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import numpy as np
4+
import pandas.util.testing as tm
5+
from pandas.util.testing import assert_copy
6+
7+
8+
def test_astype(idx):
9+
expected = idx.copy()
10+
actual = idx.astype('O')
11+
assert_copy(actual.levels, expected.levels)
12+
assert_copy(actual.labels, expected.labels)
13+
assert [level.name for level in actual.levels] == list(expected.names)
14+
15+
with tm.assert_raises_regex(TypeError, "^Setting.*dtype.*object"):
16+
idx.astype(np.dtype(int))

pandas/tests/indexes/multi/test_constructor.py

+75-53
Original file line numberDiff line numberDiff line change
@@ -234,29 +234,31 @@ def test_from_arrays_empty():
234234
tm.assert_index_equal(result, expected)
235235

236236

237-
def test_from_arrays_invalid_input():
237+
@pytest.mark.parametrize('invalid_array', [
238+
(1),
239+
([1]),
240+
([1, 2]),
241+
([[1], 2]),
242+
('a'),
243+
(['a']),
244+
(['a', 'b']),
245+
([['a'], 'b']),
246+
])
247+
def test_from_arrays_invalid_input(invalid_array):
238248
invalid_inputs = [1, [1], [1, 2], [[1], 2],
239249
'a', ['a'], ['a', 'b'], [['a'], 'b']]
240250
for i in invalid_inputs:
241251
pytest.raises(TypeError, MultiIndex.from_arrays, arrays=i)
242252

243253

244-
def test_from_arrays_different_lengths():
254+
@pytest.mark.parametrize('idx1, idx2', [
255+
pytest.param([1, 2, 3], ['a', 'b']),
256+
pytest.param([], ['a', 'b']),
257+
pytest.param([1, 2, 3], [])
258+
]
259+
)
260+
def test_from_arrays_different_lengths(idx1, idx2):
245261
# see gh-13599
246-
idx1 = [1, 2, 3]
247-
idx2 = ['a', 'b']
248-
tm.assert_raises_regex(ValueError, '^all arrays must '
249-
'be same length$',
250-
MultiIndex.from_arrays, [idx1, idx2])
251-
252-
idx1 = []
253-
idx2 = ['a', 'b']
254-
tm.assert_raises_regex(ValueError, '^all arrays must '
255-
'be same length$',
256-
MultiIndex.from_arrays, [idx1, idx2])
257-
258-
idx1 = [1, 2, 3]
259-
idx2 = []
260262
tm.assert_raises_regex(ValueError, '^all arrays must '
261263
'be same length$',
262264
MultiIndex.from_arrays, [idx1, idx2])
@@ -305,35 +307,41 @@ def test_from_tuples_index_values(idx):
305307
assert (result.values == idx.values).all()
306308

307309

308-
def test_from_product_empty():
310+
def test_from_product_empty_zero_levels():
309311
# 0 levels
310312
with tm.assert_raises_regex(
311313
ValueError, "Must pass non-zero number of levels/labels"):
312314
MultiIndex.from_product([])
313315

314-
# 1 level
316+
317+
def test_from_product_empty_one_level():
315318
result = MultiIndex.from_product([[]], names=['A'])
316319
expected = pd.Index([], name='A')
317320
tm.assert_index_equal(result.levels[0], expected)
318321

319-
# 2 levels
320-
l1 = [[], ['foo', 'bar', 'baz'], []]
321-
l2 = [[], [], ['a', 'b', 'c']]
322+
323+
@pytest.mark.parametrize('first, second', [
324+
([], []),
325+
(['foo', 'bar', 'baz'], []),
326+
([], ['a', 'b', 'c']),
327+
])
328+
def test_from_product_empty_two_levels(first, second):
322329
names = ['A', 'B']
323-
for first, second in zip(l1, l2):
324-
result = MultiIndex.from_product([first, second], names=names)
325-
expected = MultiIndex(levels=[first, second],
326-
labels=[[], []], names=names)
327-
tm.assert_index_equal(result, expected)
330+
result = MultiIndex.from_product([first, second], names=names)
331+
expected = MultiIndex(levels=[first, second],
332+
labels=[[], []], names=names)
333+
tm.assert_index_equal(result, expected)
334+
328335

336+
@pytest.mark.parametrize('N', list(range(4)))
337+
def test_from_product_empty_three_levels(N):
329338
# GH12258
330339
names = ['A', 'B', 'C']
331-
for N in range(4):
332-
lvl2 = lrange(N)
333-
result = MultiIndex.from_product([[], lvl2, []], names=names)
334-
expected = MultiIndex(levels=[[], lvl2, []],
335-
labels=[[], [], []], names=names)
336-
tm.assert_index_equal(result, expected)
340+
lvl2 = lrange(N)
341+
result = MultiIndex.from_product([[], lvl2, []], names=names)
342+
expected = MultiIndex(levels=[[], lvl2, []],
343+
labels=[[], [], []], names=names)
344+
tm.assert_index_equal(result, expected)
337345

338346

339347
def test_from_product_invalid_input():
@@ -352,19 +360,24 @@ def test_from_product_datetimeindex():
352360
tm.assert_numpy_array_equal(mi.values, etalon)
353361

354362

355-
def test_from_product_index_series_categorical():
363+
@pytest.mark.parametrize('ordered', [False, True])
364+
@pytest.mark.parametrize('f', [
365+
lambda x: x,
366+
lambda x: pd.Series(x),
367+
lambda x: x.values
368+
])
369+
def test_from_product_index_series_categorical(ordered, f):
356370
# GH13743
357371
first = ['foo', 'bar']
358-
for ordered in [False, True]:
359-
idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"),
360-
ordered=ordered)
361-
expected = pd.CategoricalIndex(list("abcaab") + list("abcaab"),
362-
categories=list("bac"),
363-
ordered=ordered)
364372

365-
for arr in [idx, pd.Series(idx), idx.values]:
366-
result = pd.MultiIndex.from_product([first, arr])
367-
tm.assert_index_equal(result.get_level_values(1), expected)
373+
idx = pd.CategoricalIndex(list("abcaab"), categories=list("bac"),
374+
ordered=ordered)
375+
expected = pd.CategoricalIndex(list("abcaab") + list("abcaab"),
376+
categories=list("bac"),
377+
ordered=ordered)
378+
379+
result = pd.MultiIndex.from_product([first, f(idx)])
380+
tm.assert_index_equal(result.get_level_values(1), expected)
368381

369382

370383
def test_from_product():
@@ -409,19 +422,28 @@ def test_create_index_existing_name(idx):
409422
index = idx
410423
index.names = ['foo', 'bar']
411424
result = pd.Index(index)
412-
tm.assert_index_equal(
413-
result, Index(Index([('foo', 'one'), ('foo', 'two'),
414-
('bar', 'one'), ('baz', 'two'),
415-
('qux', 'one'), ('qux', 'two')],
416-
dtype='object'),
417-
names=['foo', 'bar']))
425+
expected = Index(
426+
Index([
427+
('foo', 'one'), ('foo', 'two'),
428+
('bar', 'one'), ('baz', 'two'),
429+
('qux', 'one'), ('qux', 'two')],
430+
dtype='object'
431+
),
432+
names=['foo', 'bar']
433+
)
434+
tm.assert_index_equal(result, expected)
418435

419436
result = pd.Index(index, names=['A', 'B'])
420-
tm.assert_index_equal(
421-
result,
422-
Index(Index([('foo', 'one'), ('foo', 'two'), ('bar', 'one'),
423-
('baz', 'two'), ('qux', 'one'), ('qux', 'two')],
424-
dtype='object'), names=['A', 'B']))
437+
expected = Index(
438+
Index([
439+
('foo', 'one'), ('foo', 'two'),
440+
('bar', 'one'), ('baz', 'two'),
441+
('qux', 'one'), ('qux', 'two')],
442+
dtype='object'
443+
),
444+
names=['A', 'B']
445+
)
446+
tm.assert_index_equal(result, expected)
425447

426448

427449
def test_tuples_with_name_string():

pandas/tests/indexes/multi/test_copy.py

+45-83
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
from copy import copy, deepcopy
44

55
import pandas.util.testing as tm
6-
from pandas import (CategoricalIndex, IntervalIndex, MultiIndex, PeriodIndex,
7-
RangeIndex, Series, compat)
6+
import pytest
7+
from pandas import MultiIndex
88

99

1010
def assert_multiindex_copied(copy, original):
@@ -41,84 +41,46 @@ def test_view(idx):
4141
assert_multiindex_copied(i_view, idx)
4242

4343

44-
def test_copy_name(idx):
45-
# gh-12309: Check that the "name" argument
46-
# passed at initialization is honored.
47-
48-
# TODO: Remove or refactor MultiIndex not tested.
49-
for name, index in compat.iteritems({'idx': idx}):
50-
if isinstance(index, MultiIndex):
51-
continue
52-
53-
first = index.__class__(index, copy=True, name='mario')
54-
second = first.__class__(first, copy=False)
55-
56-
# Even though "copy=False", we want a new object.
57-
assert first is not second
58-
59-
# Not using tm.assert_index_equal() since names differ.
60-
assert index.equals(first)
61-
62-
assert first.name == 'mario'
63-
assert second.name == 'mario'
64-
65-
s1 = Series(2, index=first)
66-
s2 = Series(3, index=second[:-1])
67-
68-
if not isinstance(index, CategoricalIndex):
69-
# See gh-13365
70-
s3 = s1 * s2
71-
assert s3.index.name == 'mario'
72-
73-
74-
def test_ensure_copied_data(idx):
75-
# Check the "copy" argument of each Index.__new__ is honoured
76-
# GH12309
77-
# TODO: REMOVE THIS TEST. MultiIndex is tested seperately as noted below.
78-
79-
for name, index in compat.iteritems({'idx': idx}):
80-
init_kwargs = {}
81-
if isinstance(index, PeriodIndex):
82-
# Needs "freq" specification:
83-
init_kwargs['freq'] = index.freq
84-
elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)):
85-
# RangeIndex cannot be initialized from data
86-
# MultiIndex and CategoricalIndex are tested separately
87-
continue
88-
89-
index_type = index.__class__
90-
result = index_type(index.values, copy=True, **init_kwargs)
91-
tm.assert_index_equal(index, result)
92-
tm.assert_numpy_array_equal(index.values, result.values,
93-
check_same='copy')
94-
95-
if isinstance(index, PeriodIndex):
96-
# .values an object array of Period, thus copied
97-
result = index_type(ordinal=index.asi8, copy=False,
98-
**init_kwargs)
99-
tm.assert_numpy_array_equal(index._ndarray_values,
100-
result._ndarray_values,
101-
check_same='same')
102-
elif isinstance(index, IntervalIndex):
103-
# checked in test_interval.py
104-
pass
105-
else:
106-
result = index_type(index.values, copy=False, **init_kwargs)
107-
tm.assert_numpy_array_equal(index.values, result.values,
108-
check_same='same')
109-
tm.assert_numpy_array_equal(index._ndarray_values,
110-
result._ndarray_values,
111-
check_same='same')
112-
113-
114-
def test_copy_and_deepcopy(indices):
115-
116-
if isinstance(indices, MultiIndex):
117-
return
118-
for func in (copy, deepcopy):
119-
idx_copy = func(indices)
120-
assert idx_copy is not indices
121-
assert idx_copy.equals(indices)
122-
123-
new_copy = indices.copy(deep=True, name="banana")
124-
assert new_copy.name == "banana"
44+
@pytest.mark.parametrize('func', [copy, deepcopy])
45+
def test_copy_and_deepcopy(func):
46+
47+
idx = MultiIndex(
48+
levels=[['foo', 'bar'], ['fizz', 'buzz']],
49+
labels=[[0, 0, 0, 1], [0, 0, 1, 1]],
50+
names=['first', 'second']
51+
)
52+
idx_copy = func(idx)
53+
assert idx_copy is not idx
54+
assert idx_copy.equals(idx)
55+
56+
57+
@pytest.mark.parametrize('deep', [True, False])
58+
def test_copy_method(deep):
59+
idx = MultiIndex(
60+
levels=[['foo', 'bar'], ['fizz', 'buzz']],
61+
labels=[[0, 0, 0, 1], [0, 0, 1, 1]],
62+
names=['first', 'second']
63+
)
64+
idx_copy = idx.copy(deep=deep)
65+
assert idx_copy.equals(idx)
66+
67+
68+
@pytest.mark.parametrize('deep', [True, False])
69+
@pytest.mark.parametrize('kwarg, value', [
70+
('names', ['thrid', 'fourth']),
71+
('levels', [['foo2', 'bar2'], ['fizz2', 'buzz2']]),
72+
('labels', [[1, 0, 0, 0], [1, 1, 0, 0]])
73+
])
74+
def test_copy_method_kwargs(deep, kwarg, value):
75+
# gh-12309: Check that the "name" argument as well other kwargs are honored
76+
idx = MultiIndex(
77+
levels=[['foo', 'bar'], ['fizz', 'buzz']],
78+
labels=[[0, 0, 0, 1], [0, 0, 1, 1]],
79+
names=['first', 'second']
80+
)
81+
82+
idx_copy = idx.copy(**{kwarg: value, 'deep': deep})
83+
if kwarg == 'names':
84+
assert getattr(idx_copy, kwarg) == value
85+
else:
86+
assert list(list(i) for i in getattr(idx_copy, kwarg)) == value

pandas/tests/indexes/multi/test_format.py

-5
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,6 @@ def test_repr_roundtrip():
100100
tm.assert_index_equal(result, mi_u, exact=True)
101101

102102

103-
def test_str():
104-
# tested elsewhere
105-
pass
106-
107-
108103
def test_unicode_string_with_unicode():
109104
d = {"a": [u("\u05d0"), 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}
110105
idx = pd.DataFrame(d).set_index(["a", "b"]).index

0 commit comments

Comments
 (0)