Skip to content

BUG: DataFrame.sort_index() ignores the values returned by the key function #56224

@n-splv

Description

@n-splv

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

def sort_function(idx: pd.Index) -> pd.Index:
    print(f"Called with {idx=}")
    return sorted(idx)


df = pd.DataFrame(
    {"col": [1, 9, 4]},
    index=[1, 3, 2]
)
df.sort_index(key=sort_function)

Issue Description

Result:

Called with idx=Index([1, 3, 2], dtype='int64')
    col
1	1
3	9
2	4

Expected Behavior

Must be:

Called with idx=Index([1, 3, 2], dtype='int64')
    col
1	1
2	4
3	9

Installed Versions

>>> pd.__version__
'2.1.3'

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions