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(axis=1, ascending=True)
# ascending=True 昇順
# ascending=False 降順

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

import pandas as pd

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

print(d)

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

d = d.sort_index(axis=1, ascending=True)

print(d)

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

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

d = d.sort_index(axis=1, ascending=False)

print(d)

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