python pandasでDataFrameをインデックス名でソートする

python pandasでDataFrameをインデックス名でソートする

pythonで、ライブラリpandasのsort_indexを使用して、DataFrameをインデックス名でソートするサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

pandasインストール

pandasをインストールされていない方は、pipでインストールしておきます。

pip install pandas

# Successfully installed pandas-1.1.4

sort_index使い方

sort_indexを使用すると、DataFrameをインデックス名でソートするが可能です。

import pandas as pd

DataFrameObj.sort_index(ascending=True)
# ascending=True 昇順
# ascending=False 降順

以下は、DataFrameをインデックス名を昇順でソートするサンプルコードとなります。

import pandas as pd

# データフレームの初期化
d = pd.DataFrame({
        'a': [25, 22, 23],
        'b': [11, 12, 13],
        'c': [31, 32, 33]
    },
    index = ['2', '1', '3']
)

print(d)

#     a   b   c
# 2  25  11  31
# 1  22  12  32
# 3  23  13  33

d = d.sort_index(ascending=True)

print(d)

#     a   b   c
# 1  22  12  32
# 2  25  11  31
# 3  23  13  33

降順の場合は、以下の結果となります。

d = d.sort_index(ascending=False)

print(d)

#     a   b   c
# 3  23  13  33
# 2  25  11  31
# 1  22  12  32

元の値も変更する場合は、オプションに「inplace=True」を使用します。

import pandas as pd

# データフレームの初期化
d = pd.DataFrame({
        'a': [25, 22, 23],
        'b': [11, 12, 13],
        'c': [31, 32, 33]
    },
    index = ['2', '1', '3']
)

d.sort_index(ascending=False)

print(d)
#     a   b   c
# 2  25  11  31
# 1  22  12  32
# 3  23  13  33

d.sort_index(ascending=False,inplace=True)

print(d)

#     a   b   c
# 3  23  13  33
# 2  25  11  31
# 1  22  12  32