Skip to content

DOC: Added docs to clarify that MultiIndex.set_levels() interprets passed values as new components of the .levels attribute (#28294) #28797

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 122 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
122 commits
Select commit Hold shift + click to select a range
e8256cc
DOC: added docs for MultiIndex.set_levels (#28294)
hweecat Oct 5, 2019
d9130f2
edit set_levels docstring with additional examples
hweecat Oct 8, 2019
46d88c1
CLN: Exception*2 in groupby wrapper (#28771)
jbrockmendel Oct 8, 2019
1ef3637
TST: un-xfail 1 passing maybe_promote test (#28850)
jbrockmendel Oct 8, 2019
f625730
remove doc note about apply applying a function to the first element …
tlynch1315 Oct 8, 2019
c9b6261
TST: un-xfail 22 tests (#28856)
jbrockmendel Oct 8, 2019
25b1859
TST: Improve compatibility with pypy error messages (#28844)
rlamy Oct 8, 2019
29e56df
TST: Fix not-boxed maybe_promote test (#28852)
jbrockmendel Oct 8, 2019
acde02b
TST: fix 24 xfails in maybe_promote (#28833)
jbrockmendel Oct 8, 2019
5122241
CLN: Assorted cleanups (#28848)
jbrockmendel Oct 8, 2019
df2e081
Clean up Abstract and Naming Definitions for GroupBy (#28847)
WillAyd Oct 8, 2019
43687c0
DOC: Fix missing periods and non capitalized summary beginnings (#28858)
refactoriel Oct 9, 2019
93183ba
fix unnecessary sort in pd.read_json and orient="index" (#28606)
KimDoubleB Oct 9, 2019
71f8ab9
CLN: dont catch Exception in groupby var (#28883)
jbrockmendel Oct 10, 2019
548f83d
CLN: dont catch on groupby.mean (#28878)
jbrockmendel Oct 10, 2019
5cbd82b
CLN: assorted cleanups, remove unicode checks in cython (#28879)
jbrockmendel Oct 10, 2019
fcea0dc
No catching needed for median (#28873)
jbrockmendel Oct 10, 2019
959a760
read_hdf closes HDF5 stores that it didn't open. (#28700)
kboone Oct 10, 2019
4f97ca4
DOC: Fix commpiler typo in contributing.rst (#28891)
shaido987 Oct 10, 2019
9743154
TST: Fix maybe_promote floating non-boxed tests (#28880)
jbrockmendel Oct 10, 2019
9a3e1ef
TST: Fix xfails for non-box maybe_promote on integer dtypes (#28864)
jbrockmendel Oct 10, 2019
eca6079
pandas.io.formats.style.Styler.set_table_attributes: Parameter attrib…
roshni-b Oct 10, 2019
0c4404b
DOC: Fixed PR06 errors in pandas.api.extensions.ExtensionArray (#28885)
roshni-b Oct 10, 2019
de2e086
REF: simplify maybe_promote (#28899)
jbrockmendel Oct 10, 2019
d8f9be7
Fix typo (#28915)
KimDoubleB Oct 11, 2019
230a61a
TYPING: lockdown test modules failing mypy (#28914)
simonjayhawkins Oct 11, 2019
fab2c90
CLN: simplify maybe_promote in float and complex cases (#28913)
jbrockmendel Oct 11, 2019
e1e51df
TYPING: errors reported by mypy 0.730 (#28910)
simonjayhawkins Oct 11, 2019
a4c92ca
clean tests/indexing/common.py (#28904)
topper-123 Oct 11, 2019
3954fa7
REF: use fused types for groupby_helper (#28886)
jbrockmendel Oct 11, 2019
6241b9d
BUG: Allow all int types for merge (GH28870) (#28875)
jjlkant Oct 11, 2019
0474c7f
TST: Fix 36 maybe_promote xfails wanting np.bytes_ instead of np.obje…
jbrockmendel Oct 11, 2019
3fba92e
TYPING: fix type annotation for pandas.io.formats.format._binify (#28…
simonjayhawkins Oct 11, 2019
894eac6
TST: add test coverage for maybe_promote (#23982)
h-vetinari Oct 11, 2019
981299c
TST: Use fixtures instead of setup_method for index tests (#28865)
jschendel Oct 11, 2019
7ea5c96
CLN: Exception (#28853)
jbrockmendel Oct 11, 2019
a31e160
CLN: assorted cleanups, mostly post-black fixups (#28857)
jbrockmendel Oct 11, 2019
0748c91
DOC: PR06 docstring fixes (#28807)
tolaa001 Oct 11, 2019
54b1151
TST: Allow for multiple variables on the same line in docstring valid…
ChiefMilesEdgeworth Oct 11, 2019
d6b058d
CLN: try/except cleanups (#28939)
jbrockmendel Oct 12, 2019
c387a28
BUG: Avoid undefined behaviour when converting from float to timedelt…
siddhesh Oct 12, 2019
fad037e
Added note to 'contributing.rst file', telling users to append GH Iss…
S3rbane Oct 12, 2019
4ade26b
REF: maybe_promote refactor/cleanup (#28897)
jbrockmendel Oct 12, 2019
1e92886
API: Add various deprecated attributes to ._deprecated (#28805)
topper-123 Oct 12, 2019
56b2fd8
TST: Test pivot_table() with categorical data (#28803)
ryankarlos Oct 12, 2019
25059ee
BUG: Need 'windows-1252' encoding for locale names. (#27368)
timcera Oct 12, 2019
f7d162b
DOC: disable nbsphinx including requirejs (#28940)
jorisvandenbossche Oct 12, 2019
625c550
CLN: fix mypy errors in pandas/tests/extension/test_numpy.py #28926 (…
lukasbk Oct 13, 2019
0eee324
TST: add test_series_any_timedelta for GH17667 (#28942)
rohitsanj Oct 13, 2019
2931f02
PR06 doc string fixes (#28946)
tolaa001 Oct 13, 2019
04d7931
fix #28926 pandas\api\test_api.py mypy errors (#28935)
yogendrasoni Oct 13, 2019
06a6b49
Eliminated _WriterBase class, removed unused fixtures from methods in…
dayoreke Oct 13, 2019
851ca1a
Fix mypy errors for pandas\tests\* #28926 (test_algos.py) (#28960)
lrm25 Oct 14, 2019
18a9e4c
DOC: Fixed PR08 and PR09 docstring errors in pandas.Series (#28845)
jb8429 Oct 14, 2019
2f80feb
BUG: Partial fix for docstring validation for parameters (#28765)
ChiefMilesEdgeworth Oct 14, 2019
5b0bf23
DOC: fix formatting in the ExtensionArray docstrings (#28686)
HughKelley Oct 14, 2019
8c5941c
BUG: use EA.astype in ExtensionBlock.to_native_types (#28841)
jorisvandenbossche Oct 14, 2019
97c6567
Document 3.8 compatibility (#28982)
TomAugspurger Oct 15, 2019
80412cc
CI: 3.8 build (#28730)
jbrockmendel Oct 15, 2019
c65cfb6
remove unnecessary get_value_at calls (#28977)
jbrockmendel Oct 15, 2019
3eca505
add types tot rank_1d_, rank_2d (#28978)
jbrockmendel Oct 15, 2019
3b34368
CLN: Exception in _libs (#28967)
jbrockmendel Oct 15, 2019
125739f
CLN: pandas-dev#28926 Fix pandas/tests/tseries/offsets/test_offsets_p…
aaditya-panik Oct 15, 2019
6dc53bb
CLN: pandas-dev#28926 Fix mypy errors in pandas/tests/io/parser/conft…
aaditya-panik Oct 15, 2019
19c8fad
DOC: 0.25.2 whatsnew cleanup (#29000)
TomAugspurger Oct 15, 2019
8d3fec9
DOC: fix is_scalar documentation (#28998) (#29004)
andreasbuhr Oct 15, 2019
74bbbb0
Setuptools CI fixup (#29010)
TomAugspurger Oct 15, 2019
de67bb7
CLN: Fix mypy errors in pandas/tests/io/test_sql.py Reverted and adde…
aaditya-panik Oct 16, 2019
d52850f
DOC: Reference level name as Term of HDFStore.select query (#28791) (…
nrebena Oct 16, 2019
0a108f0
CLN: move small bits outside of try/excepts (#28962)
jbrockmendel Oct 16, 2019
c903e5e
CLN: Consistent and Annotated Return Type of _iterate_slices (#28958)
WillAyd Oct 16, 2019
b632ca0
restore xfail (#29013)
jbrockmendel Oct 16, 2019
79a5f7c
To html encoding add (#28692)
Oct 16, 2019
a0d01b8
add uint64 support for some libgroupby funcs (#28931)
jbrockmendel Oct 16, 2019
86e187f
BUG: CategoricalIndex allowed reindexing duplicate sources (#28257)
batterseapower Oct 16, 2019
46e89b0
Separate MultiIndex names from levels (#27242)
topper-123 Oct 16, 2019
5ad908e
DOC: fix code-block in the reshaping docs (#28838)
oktaysabak Oct 16, 2019
fdc322a
CLN: Fix mypy error in pandas/tests/computation/test_eval.py (#29007)
immaxchen Oct 16, 2019
b63f829
CLN: Clean DirNameMixin (#28957)
topper-123 Oct 16, 2019
bff90a3
REF: de-duplicate groupby_helper code (#28934)
jbrockmendel Oct 16, 2019
30a0e2e
CLN: fix mypy error pandas/tests/plotting/test_backend.py (#29016)
saska Oct 16, 2019
143eb38
REF: re-raise AssertionError unchanged (#28959)
jbrockmendel Oct 16, 2019
9486f04
tests/indexing/test_coercion.py typefix (#28990)
lukasbk Oct 16, 2019
da3d0d9
DEPR: remove previously-deprecated broadcast/reduce kwargs from DataF…
jbrockmendel Oct 16, 2019
9d45934
BUG: Fix TypeError in _cython_agg_blocks (#29035)
jbrockmendel Oct 17, 2019
509eb14
CI: xfail on numpy 1.18 (#29057)
jbrockmendel Oct 17, 2019
6d35836
Stop catching TypeError in groupby methods (#29060)
jbrockmendel Oct 17, 2019
b0f33b3
API: Restore getting name from MultiIndex level (#29061)
TomAugspurger Oct 18, 2019
709436d
fixed issue of mypy for test_ujson (#29022)
iamrajhans Oct 18, 2019
f556a71
CLN: derivation of nogil param (#29047)
jbrockmendel Oct 18, 2019
827440a
REF: remove groupby_helper (#29040)
jbrockmendel Oct 18, 2019
1e4fe0a
ENH: Informative dtype message for for assert_series_equal (#28993)
moi90 Oct 18, 2019
2683954
TST: add regression test for all-none-groupby (#29067)
crepererum Oct 18, 2019
45dc6d3
Fix mypy errors for pandas\tests\*: test_convert_to.py (#28965)
lrm25 Oct 18, 2019
58d34d9
CLN: catch less in groupby (#29077)
jbrockmendel Oct 18, 2019
e54b995
CLN: simplify take_2d_multi (#29065)
jbrockmendel Oct 18, 2019
2701f52
REF: use fused types in algos_rank_helper (#29044)
jbrockmendel Oct 18, 2019
09a9f5f
DOC: updated categorical docstring (#29068)
javad94 Oct 18, 2019
b372ac4
CLN: tighten exception catching in indexes (#29078)
jbrockmendel Oct 19, 2019
09fc1b4
explain set_levels().levels examples + formatting
hweecat Oct 19, 2019
5bdd7db
explain set_levels().levels examples + formatting
hweecat Oct 19, 2019
9c4a371
[#22550] Remove TestData from series-tests test_quantile.py (#29096)
SaturnFromTitan Oct 19, 2019
d186f77
Merge branches 'docfix-multiindex-setlevels' and 'docfix-multiindex-s…
hweecat Oct 19, 2019
a2f5ae2
comments, catch less (#29088)
jbrockmendel Oct 19, 2019
cb99e24
REF: remove algos_rank_helper (#29086)
jbrockmendel Oct 19, 2019
930dd84
CLN: Exception in DataFrame._reduce (#29085)
jbrockmendel Oct 19, 2019
7c8c8c8
[#22550] Remove TestData from series-tests test_operators.py (#29084)
SaturnFromTitan Oct 19, 2019
e4afa45
TST: 2d index when constructing dataframe (#25416). (#29083)
jhereth Oct 19, 2019
cb76dcb
TST: regression test for groupby with datetime and timedelta (#15562)…
jhereth Oct 19, 2019
6931051
CLN: cython and docstring cleanups (#29089)
jbrockmendel Oct 19, 2019
04893a9
BUG: parse_time_string failing to raise TypeError (#29098)
jbrockmendel Oct 19, 2019
971d191
explain set_levels().levels examples + formatting
hweecat Oct 19, 2019
8ccc7c7
formatting changes
hweecat Oct 20, 2019
36803b9
formatting changes
hweecat Oct 20, 2019
e623f0f
Add a regression test for the timezone issue (#29097)
grigoriosgiann Oct 20, 2019
d2d8785
Fix typing errors (#29115)
AbhijeetKrishnan Oct 20, 2019
9f03837
Fix typing errors (#29114)
AbhijeetKrishnan Oct 20, 2019
9026a79
DOC: added docs for MultiIndex.set_levels (#28294)
hweecat Oct 5, 2019
4f5e38d
edit set_levels docstring with additional examples
hweecat Oct 8, 2019
c00cc9d
explain set_levels().levels examples + formatting
hweecat Oct 19, 2019
211574b
explain set_levels().levels examples + formatting
hweecat Oct 19, 2019
93c84bb
Merge branch 'docfix-multiindex-setlevels' of https://github.com/hwee…
hweecat Oct 21, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Separate MultiIndex names from levels (#27242)
  • Loading branch information
topper-123 authored and jreback committed Oct 16, 2019
commit 46e89b07d3c249b3e42b326db1c15deb1a2dd00e
33 changes: 32 additions & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,37 @@ source, you should no longer need to install Cython into your build environment
Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

- :class:`pandas.core.groupby.GroupBy.transform` now raises on invalid operation names (:issue:`27489`).
.. _whatsnew_1000.api_breaking.MultiIndex._names:

``MultiIndex.levels`` do not hold level names any longer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

- A :class:`MultiIndex` previously stored the level names as attributes of each of its
:attr:`MultiIndex.levels`. From Pandas 1.0, the names are only accessed through
:attr:`MultiIndex.names` (which was also possible previously). This is done in order to
make :attr:`MultiIndex.levels` more similar to :attr:`CategoricalIndex.categories` (:issue:`27242`:).

*pandas 0.25.x*

.. code-block:: ipython

In [1]: mi = pd.MultiIndex.from_product([[1, 2], ['a', 'b']], names=['x', 'y'])
Out[2]: mi
MultiIndex([(1, 'a'),
(1, 'b'),
(2, 'a'),
(2, 'b')],
names=['x', 'y'])
Out[3]: mi.levels[0].name
'x'

*pandas 1.0.0*

.. ipython:: python

mi = pd.MultiIndex.from_product([[1, 2], ['a', 'b']], names=['x', 'y'])
mi.levels[0].name

- :class:`pandas.core.arrays.IntervalArray` adopts a new ``__repr__`` in accordance with other array classes (:issue:`25022`)

*pandas 0.25.x*
Expand All @@ -150,6 +180,7 @@ Backwards incompatible API changes
Other API changes
^^^^^^^^^^^^^^^^^

- :class:`pandas.core.groupby.GroupBy.transform` now raises on invalid operation names (:issue:`27489`)
- :meth:`pandas.api.types.infer_dtype` will now return "integer-na" for integer and ``np.nan`` mix (:issue:`27283`)
- :meth:`MultiIndex.from_arrays` will no longer infer names from arrays if ``names=None`` is explicitly provided (:issue:`27292`)
- In order to improve tab-completion, Pandas does not include most deprecated attributes when introspecting a pandas object using ``dir`` (e.g. ``dir(df)``).
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7792,7 +7792,8 @@ def _count_level(self, level, axis=0, numeric_only=False):
if isinstance(level, str):
level = count_axis._get_level_number(level)

level_index = count_axis.levels[level]
level_name = count_axis._names[level]
level_index = count_axis.levels[level]._shallow_copy(name=level_name)
level_codes = ensure_int64(count_axis.codes[level])
counts = lib.count_level_2d(mask, level_codes, len(level_index), axis=0)

Expand Down
15 changes: 8 additions & 7 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ def __new__(
result._set_levels(levels, copy=copy, validate=False)
result._set_codes(codes, copy=copy, validate=False)

result._names = [None] * len(levels)
if names is not None:
# handles name validation
result._set_names(names)
Expand Down Expand Up @@ -1216,7 +1217,7 @@ def __len__(self):
return len(self.codes[0])

def _get_names(self):
return FrozenList(level.name for level in self.levels)
return FrozenList(self._names)

def _set_names(self, names, level=None, validate=True):
"""
Expand Down Expand Up @@ -1262,7 +1263,7 @@ def _set_names(self, names, level=None, validate=True):
level = [self._get_level_number(l) for l in level]

# set the name
for l, name in zip(level, names):
for lev, name in zip(level, names):
if name is not None:
# GH 20527
# All items in 'names' need to be hashable:
Expand All @@ -1272,7 +1273,7 @@ def _set_names(self, names, level=None, validate=True):
self.__class__.__name__
)
)
self.levels[l].rename(name, inplace=True)
self._names[lev] = name

names = property(
fset=_set_names, fget=_get_names, doc="""\nNames of levels in MultiIndex.\n"""
Expand Down Expand Up @@ -1582,13 +1583,13 @@ def _get_level_values(self, level, unique=False):
values : ndarray
"""

values = self.levels[level]
lev = self.levels[level]
level_codes = self.codes[level]
name = self._names[level]
if unique:
level_codes = algos.unique(level_codes)
filled = algos.take_1d(values._values, level_codes, fill_value=values._na_value)
values = values._shallow_copy(filled)
return values
filled = algos.take_1d(lev._values, level_codes, fill_value=lev._na_value)
return lev._shallow_copy(filled, name=name)

def get_level_values(self, level):
"""
Expand Down
17 changes: 9 additions & 8 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,10 @@ def get_new_values(self):
def get_new_columns(self):
if self.value_columns is None:
if self.lift == 0:
return self.removed_level
return self.removed_level._shallow_copy(name=self.removed_name)

lev = self.removed_level
return lev.insert(0, lev._na_value)
lev = self.removed_level.insert(0, item=self.removed_level._na_value)
return lev.rename(self.removed_name)

stride = len(self.removed_level) + self.lift
width = len(self.value_columns)
Expand Down Expand Up @@ -298,10 +298,10 @@ def get_new_index(self):

# construct the new index
if len(self.new_index_levels) == 1:
lev, lab = self.new_index_levels[0], result_codes[0]
if (lab == -1).any():
lev = lev.insert(len(lev), lev._na_value)
return lev.take(lab)
level, level_codes = self.new_index_levels[0], result_codes[0]
if (level_codes == -1).any():
level = level.insert(len(level), level._na_value)
return level.take(level_codes).rename(self.new_index_names[0])

return MultiIndex(
levels=self.new_index_levels,
Expand Down Expand Up @@ -661,7 +661,8 @@ def _convert_level_number(level_num, columns):
new_names = this.columns.names[:-1]
new_columns = MultiIndex.from_tuples(unique_groups, names=new_names)
else:
new_columns = unique_groups = this.columns.levels[0]
new_columns = this.columns.levels[0]._shallow_copy(name=this.columns.names[0])
unique_groups = new_columns

# time to ravel the values
new_data = {}
Expand Down
6 changes: 4 additions & 2 deletions pandas/io/json/_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,10 @@ def build_table_schema(data, index=True, primary_key=None, version=True):

if index:
if data.index.nlevels > 1:
for level in data.index.levels:
fields.append(convert_pandas_type_to_json_field(level))
for level, name in zip(data.index.levels, data.index.names):
new_field = convert_pandas_type_to_json_field(level)
new_field["name"] = name
fields.append(new_field)
else:
fields.append(convert_pandas_type_to_json_field(data.index))

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,7 @@ def test_reset_index(self, float_frame):
):
values = lev.take(level_codes)
name = names[i]
tm.assert_index_equal(values, Index(deleveled[name]))
tm.assert_index_equal(values, Index(deleveled[name].rename(name=None)))

stacked.index.names = [None, None]
deleveled2 = stacked.reset_index()
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/multi/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def test_astype(idx):
actual = idx.astype("O")
assert_copy(actual.levels, expected.levels)
assert_copy(actual.codes, expected.codes)
assert [level.name for level in actual.levels] == list(expected.names)
assert actual.names == list(expected.names)

with pytest.raises(TypeError, match="^Setting.*dtype.*object"):
idx.astype(np.dtype(int))
Expand Down
8 changes: 5 additions & 3 deletions pandas/tests/indexes/multi/test_constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def test_constructor_single_level():
levels=[["foo", "bar", "baz", "qux"]], codes=[[0, 1, 2, 3]], names=["first"]
)
assert isinstance(result, MultiIndex)
expected = Index(["foo", "bar", "baz", "qux"], name="first")
expected = Index(["foo", "bar", "baz", "qux"])
tm.assert_index_equal(result.levels[0], expected)
assert result.names == ["first"]

Expand Down Expand Up @@ -292,8 +292,9 @@ def test_from_arrays_empty():
# 1 level
result = MultiIndex.from_arrays(arrays=[[]], names=["A"])
assert isinstance(result, MultiIndex)
expected = Index([], name="A")
expected = Index([])
tm.assert_index_equal(result.levels[0], expected)
assert result.names == ["A"]

# N levels
for N in [2, 3]:
Expand Down Expand Up @@ -439,8 +440,9 @@ def test_from_product_empty_zero_levels():

def test_from_product_empty_one_level():
result = MultiIndex.from_product([[]], names=["A"])
expected = pd.Index([], name="A")
expected = pd.Index([])
tm.assert_index_equal(result.levels[0], expected)
assert result.names == ["A"]


@pytest.mark.parametrize(
Expand Down
28 changes: 12 additions & 16 deletions pandas/tests/indexes/multi/test_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,25 @@ def test_index_name_retained():


def test_changing_names(idx):

# names should be applied to levels
level_names = [level.name for level in idx.levels]
check_level_names(idx, idx.names)
assert [level.name for level in idx.levels] == [None, None]

view = idx.view()
copy = idx.copy()
shallow_copy = idx._shallow_copy()

# changing names should change level names on object
# changing names should not change level names on object
new_names = [name + "a" for name in idx.names]
idx.names = new_names
check_level_names(idx, new_names)
check_level_names(idx, [None, None])

# but not on copies
check_level_names(view, level_names)
check_level_names(copy, level_names)
check_level_names(shallow_copy, level_names)
# and not on copies
check_level_names(view, [None, None])
check_level_names(copy, [None, None])
check_level_names(shallow_copy, [None, None])

# and copies shouldn't change original
shallow_copy.names = [name + "c" for name in shallow_copy.names]
check_level_names(idx, new_names)
check_level_names(idx, [None, None])


def test_take_preserve_name(idx):
Expand Down Expand Up @@ -82,9 +79,9 @@ def test_copy_names():
def test_names(idx, index_names):

# names are assigned in setup
names = index_names
assert index_names == ["first", "second"]
level_names = [level.name for level in idx.levels]
assert names == level_names
assert level_names == [None, None]

# setting bad names on existing
index = idx
Expand All @@ -109,11 +106,10 @@ def test_names(idx, index_names):
names=["first", "second", "third"],
)

# names are assigned
# names are assigned on index, but not transferred to the levels
index.names = ["a", "b"]
ind_names = list(index.names)
level_names = [level.name for level in index.levels]
assert ind_names == level_names
assert level_names == [None, None]


def test_duplicate_level_names_access_raises(idx):
Expand Down
10 changes: 4 additions & 6 deletions pandas/tests/indexes/multi/test_reindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@
import pandas.util.testing as tm


def check_level_names(index, names):
assert [level.name for level in index.levels] == list(names)


def test_reindex(idx):
result, indexer = idx.reindex(list(idx[:4]))
assert isinstance(result, MultiIndex)
check_level_names(result, idx[:4].names)
assert result.names == ["first", "second"]
assert [level.name for level in result.levels] == [None, None]

result, indexer = idx.reindex(list(idx))
assert isinstance(result, MultiIndex)
assert indexer is None
check_level_names(result, idx.names)
assert result.names == ["first", "second"]
assert [level.name for level in result.levels] == [None, None]


def test_reindex_level(idx):
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/indexes/multi/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ def test_insert(idx):
# key not contained in all levels
new_index = idx.insert(0, ("abc", "three"))

exp0 = Index(list(idx.levels[0]) + ["abc"], name="first")
exp0 = Index(list(idx.levels[0]) + ["abc"])
tm.assert_index_equal(new_index.levels[0], exp0)
assert new_index.names == ["first", "second"]

exp1 = Index(list(idx.levels[1]) + ["three"], name="second")
exp1 = Index(list(idx.levels[1]) + ["three"])
tm.assert_index_equal(new_index.levels[1], exp1)
assert new_index[0] == ("abc", "three")

Expand Down
12 changes: 6 additions & 6 deletions pandas/tests/reshape/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1219,8 +1219,10 @@ def test_concat_keys_specific_levels(self):
names=["group_key"],
)

tm.assert_index_equal(result.columns.levels[0], Index(level, name="group_key"))
assert result.columns.names[0] == "group_key"
tm.assert_index_equal(result.columns.levels[0], Index(level))
tm.assert_index_equal(result.columns.levels[1], Index([0, 1, 2, 3]))

assert result.columns.names == ["group_key", None]

def test_concat_dataframe_keys_bug(self, sort):
t1 = DataFrame(
Expand Down Expand Up @@ -1409,10 +1411,8 @@ def test_concat_keys_and_levels(self):
keys=[("foo", "one"), ("foo", "two"), ("baz", "one"), ("baz", "two")],
names=["first", "second"],
)
assert result.index.names == ("first", "second") + (None,)
tm.assert_index_equal(
result.index.levels[0], Index(["baz", "foo"], name="first")
)
assert result.index.names == ("first", "second", None)
tm.assert_index_equal(result.index.levels[0], Index(["baz", "foo"]))

def test_concat_keys_levels_no_overlap(self):
# GH #1406
Expand Down
5 changes: 2 additions & 3 deletions pandas/tests/reshape/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,16 +618,15 @@ def test_reshaping_multi_index_categorical(self):
df.index.names = ["major", "minor"]
df["str"] = "foo"

dti = df.index.levels[0]

df["category"] = df["str"].astype("category")
result = df["category"].unstack()

dti = df.index.levels[0]
c = Categorical(["foo"] * len(dti))
expected = DataFrame(
{"A": c.copy(), "B": c.copy(), "C": c.copy(), "D": c.copy()},
columns=Index(list("ABCD"), name="minor"),
index=dti,
index=dti.rename("major"),
)
tm.assert_frame_equal(result, expected)

Expand Down
Loading