Skip to content

Reording a multiindex by only specifiying the order on level 0 #4088

Closed
@jankatins

Description

@jankatins

starting PR is here: #6647

By reading the docs on Dataframe.reindex(), I would have guessed (not sure what "broadcast" is...) that this works:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = zip(*arrays)
index = MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = DataFrame({"a":list("abcdefgh"), "b":list("abcdefgh")}, index=index)
order = ["baz", "bar", "foo", "qux"]
df.reindex(order, level=0) # still returns the same ordering

It works that way on a normal index (without the level argument):

df2 = DataFrame({"a":list("ABCD")}, index=['bar', 'baz', 'foo', 'qux'])
df2.reindex(order) # new ordering

It also works when I pass a list of tuples:

_new_index = []
for _a in order:
    for _b in df.index.levels[1]:
        _new_index.append((_a, _b))
df.reindex(_new_index) # new ordering

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions