pandasデータフレームの列の入れ替え【Python3】
この記事では、Python3におけるpandasデータフレームの列の入れ替え方をご紹介いたします。使うデータはこちら→サンプルcsvファイル
まずはデータを読み込みます。
import pandas as pd
#ファイルの読み込み
df = pd.read_csv("sample_short.csv")
#データの確認
print(df)以下のようなデータになっております。
number age blood_pressure lung_capacity sex weight disease
0 1 22 110 4300 M 79 1
1 2 23 128 4500 M 65 1
2 3 24 104 3900 F 53 0
3 4 25 112 3000 F 45 0
4 5 27 108 4800 M 80 0.ix[[行のリスト],[列のリスト]]で指定
列を入れ替えたい場合は、.ix[[行のリスト],[列のリスト]]で入れ替えたい部分を指定します。以下にサンプルプログラムを示します。
#4列目と2列目をチェンジ
print(df.ix[:,[0,1,4,3,2,5,6]])
#age列とweight列をチェンジ
print(df.ix[:,["number","weight","sex","lung_capacity","blood_pressure","age","disease"]])このように、数値でも列名でも指定が可能です。
それぞれ以下のように列名が並び変わります。
number age sex lung_capacity blood_pressure weight disease
0 1 22 M 4300 110 79 1
1 2 23 M 4500 128 65 1
2 3 24 F 3900 104 53 0
3 4 25 F 3000 112 45 0
4 5 27 M 4800 108 80 0
number weight sex lung_capacity blood_pressure age disease
0 1 79 M 4300 110 22 1
1 2 65 M 4500 128 23 1
2 3 53 F 3900 104 24 0
3 4 45 F 3000 112 25 0
4 5 80 M 4800 108 27 0以下のように全列ではなく、使いたい列だけを取り出すことも可能。
print(df.ix[:,[0,1,4,3,2]])
number age sex lung_capacity blood_pressure
0 1 22 M 4300 110
1 2 23 M 4500 128
2 3 24 F 3900 104
3 4 25 F 3000 112
4 5 27 M 4800 108カテゴリ: Python

関連するサービス
記事の筆者

AVILEN編集部
株式会社AVILEN

