Skip to content

DataFrame.sort_index() with ascending passed as a list on a single level index gives wrong result #32334

Closed
@aniaan

Description

@aniaan

I found some problems while using data_frame sort_index, first, create dataframe

data = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
data = data.set_index('a')
data.sort_index(level=['a'], ascending=[False])

Then I want to sort index "a" in descending order,

data.sort_index(level=['a'], ascending=[False])

The above code does not sort index a in descending order, I found the reason is that this dataframe is a single index structure, so when ascending = list is passed, it does not take effect

pandas/pandas/core/frame.py

Lines 4777 to 4783 in bf613c1

if level is not None:
new_axis, indexer = labels.sortlevel(
level, ascending=ascending, sort_remaining=sort_remaining
)
elif isinstance(labels, ABCMultiIndex):

Because when it is used, the index may be single index or multi-index. In order to use the effect uniformly,I think there should be a judgment here. If index is a single index and ascending type == list, ascending should be equal to ascending [0],This may be more user friendly

If yes, can I mention pr

Metadata

Metadata

Labels

AlgosNon-arithmetic algos: value_counts, factorize, sorting, isin, clip, shift, diffBugIndexRelated to the Index class or subclassesgood first issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions