Skip to content

Rows order when using slice(None) on MultiIndex Dataframe.loc #31330

Closed
@nrebena

Description

@nrebena

Code Sample

df = pd.DataFrame(
      np.arange(12).reshape((4, 3)),
      index=[["a", "a", "b", "b"], [1, 2, 1, 2]],
      columns=[["Ohio", "Ohio", "Colorado"], ["Green", "Red", "Green"]],
      )

df.loc[(slice(None), [2,1]), :]                                                                                                
# actual output, same as df, order of slice(None) level take absolut precedence
     Ohio     Colorado
    Green Red    Green
a 1     0   1        2
  2     3   4        5
b 1     6   7        8
  2     9  10       11

Problem description

When working on issue #22797, I came across this situation about ordering the result of loc. Should the level not explicitely requested be used when ordering the result, and how.
This may be mostly cosmetic, are one should not rely on how the resulted row are ordered, and may be a non issue. If so, feel free to close it.

Expected Output

# Second level is prioritary on first level
     Ohio     Colorado
    Green Red    Green
a 2     3   4        5
b 2     9  10       11
a 1     0   1        2
b 1     6   7        8

# ---- or ----

# Keep order of first level, then second level
     Ohio     Colorado
    Green Red    Green
a 2     3   4        5
  1     0   1        2
b 2     9  10       11
  1     6   7        8

Metadata

Metadata

Assignees

No one assigned

    Labels

    API - ConsistencyInternal Consistency of API/BehaviorBugIndexingRelated to indexing on series/frames, not to indexes themselvesMultiIndex

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions