Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

pandas.DataFrame.sort_index#

DataFrame.sort_index(*,axis=0,level=None,ascending=True,inplace=False,kind='quicksort',na_position='last',sort_remaining=True,ignore_index=False,key=None)[source]#

Sort object by labels (along an axis).

Returns a new DataFrame sorted by label ifinplace argument isFalse, otherwise updates the original DataFrame and returns None.

Parameters:
axis{0 or ‘index’, 1 or ‘columns’}, default 0

The axis along which to sort. The value 0 identifies the rows,and 1 identifies the columns.

levelint or level name or list of ints or list of level names

If not None, sort on values in specified index level(s).

ascendingbool or list-like of bools, default True

Sort ascending vs. descending. When the index is a MultiIndex thesort direction can be controlled for each level individually.

inplacebool, default False

Whether to modify the DataFrame rather than creating a new one.

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’

Choice of sorting algorithm. See alsonumpy.sort() for moreinformation.mergesort andstable are the only stable algorithms. ForDataFrames, this option is only applied when sorting on a singlecolumn or label.

na_position{‘first’, ‘last’}, default ‘last’

Puts NaNs at the beginning iffirst;last puts NaNs at the end.Not implemented for MultiIndex.

sort_remainingbool, default True

If True and sorting by level and index is multilevel, sort by otherlevels too (in order) after sorting by specified level.

ignore_indexbool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.

keycallable, optional

If not None, apply the key function to the index valuesbefore sorting. This is similar to thekey argument in thebuiltinsorted() function, with the notable difference thatthiskey function should bevectorized. It should expect anIndex and return anIndex of the same shape. For MultiIndexinputs, the key is appliedper level.

Returns:
DataFrame or None

The original DataFrame sorted by the labels or None ifinplace=True.

See also

Series.sort_index

Sort Series by the index.

DataFrame.sort_values

Sort DataFrame by the value.

Series.sort_values

Sort Series by the value.

Examples

>>>df=pd.DataFrame([1,2,3,4,5],index=[100,29,234,1,150],...columns=['A'])>>>df.sort_index()     A1    429   2100  1150  5234  3

By default, it sorts in ascending order, to sort in descending order,useascending=False

>>>df.sort_index(ascending=False)     A234  3150  5100  129   21    4

A key function can be specified which is applied to the index beforesorting. For aMultiIndex this is applied to each level separately.

>>>df=pd.DataFrame({"a":[1,2,3,4]},index=['A','b','C','d'])>>>df.sort_index(key=lambdax:x.str.lower())   aA  1b  2C  3d  4

[8]ページ先頭

©2009-2025 Movatter.jp