Pandas DataFrame 列の順序を変更する方法
Asad Riaz 2023年1月30日 Pandas Pandas DataFrame Pandas DataFrame Column

insert
と reindex
を使用して、希望する順序で列名を割り当てるなどのさまざまな方法で、DataFrame
列の順序を変更する方法を紹介します。
Pandas で新しく希望する順序で列をリストする
最も簡単な方法は、DataFrame
に columns
のリストを再割り当てするか、必要な順序で列名を割り当てることです。
# python 3.x import pandas as pd df = pd.DataFrame( { "a": ["1", "2", "3", "4"], "b": [16, 7, 6, 16], "c": [61, 57, 16, 36], "d": ["12", "22", "13", "44"], "e": ["Green", "Red", "Blue", "Yellow"], "f": [1, 11, 23, 66], } ) print(df) df = df[["e", "c", "b", "f", "d", "a"]] print("Rearranging ..................") print("..............................") print(df)
出力:
a b c d e f 0 1 16 61 12 Green 1 1 2 7 57 22 Red 11 2 3 6 16 13 Blue 23 3 4 16 36 44 Yellow 66 Rearranging .................. .............................. e c b f d a 0 Green 61 16 1 12 1 1 Red 57 7 11 22 2 2 Blue 16 6 23 13 3 3 Yellow 36 16 66 44 4
Pandas の特定の場所を新しい列に insert
新しい列を作成する場合は、任意の場所に挿入できます。
# python 3.x import pandas as pd df = pd.DataFrame( { "a": ["1", "2", "3", "4"], "b": [16, 7, 6, 16], "c": [61, 57, 16, 36], "d": ["12", "22", "13", "44"], "e": ["Green", "Red", "Blue", "Yellow"], "f": [1, 11, 23, 66], } ) print(df) print("Inserting ..................") print("..............................") df.insert(0, "newColMean", df.mean(1)) print(df)
出力:
newColMean a b c d e f 0 26.000000 1 16 61 12 Green 1 1 25.000000 2 7 57 22 Red 11 2 15.000000 3 6 16 13 Blue 23 3 39.333333 4 16 36 44 Yellow 66
Pandas の特定の順序の reindex
列
reindex
は、おそらく列を再配置する最も効率的な方法です。
# python 3.x import pandas as pd df = pd.DataFrame( { "a": ["1", "2", "3", "4"], "b": [16, 7, 6, 16], "c": [61, 57, 16, 36], "d": ["12", "22", "13", "44"], "e": ["Green", "Red", "Blue", "Yellow"], "f": [1, 11, 23, 66], } ) print(df) print("Rearranging ..................") print("..............................") df = df.reindex(columns=["a", "f", "d", "b", "c", "e"]) print(df)
出力:
a b c d e f 0 1 16 61 12 Green 1 1 2 7 57 22 Red 11 2 3 6 16 13 Blue 23 3 4 16 36 44 Yellow 66 Rearranging .................. .............................. a f d b c e 0 1 1 12 16 61 Green 1 2 11 22 7 57 Red 2 3 23 13 6 16 Blue 3 4 66 44 16 36 Yellow
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
関連記事 - Pandas DataFrame
- Pandas DataFrame の列ヘッダーをリストとして取得する方法
- Pandas DataFrame 列を削除する方法
- Pandas で DataFrame 列を日時に変換する方法
- Pandas DataFrame で浮動小数点数 float を整数 int に変換する方法
- Pandas DataFrame を 1つの列の値で並べ替える方法
- Pandas group-by と Sum の集計を取得する方法