こんにちは、今回はpandasのDataFrameで行や列を削除する方法を解説していきます。
それぞれの役割やメリットを確認しながら基本的なポイントを押さえていきましょう。
行・列の削除に使える関数
関数 | 処理 |
---|---|
df.pop(列名) | 1列を削除する。行は削除できない。 |
del df[列名] | 複数列を削除できる。行は削除できない。 |
df.drop() | 複数行・列を削除できる 【関連記事】dropの条件や複数削除・消えない理由 |
df.dropna() | NaNのセルがある行・列を削除 【関連記事】dropnaの使い方まとめ |
df.drop_duplicates() | 重複列の削除 【関連記事】drop_duplicatesまとめ |
行や列の削除だけでもたくさんの関数がありますが、
今回はpop、del、dropの3つに関して見ていきましょう。
以下では次のDataFrameに対して処理を行っていきます。
1 2 3 4 5 6 7 8 9 10 |
import pandas as pd df = pd.DataFrame( data={'col1': [10, 20, 30, 40], 'col2': [50, 60, 70, 80], 'col3': ['a', 'b', 'c', 'd']}, index=['row1', 'row2', 'row3', 'row4'] ) df |

列の削除
1列を削除する
- popに列名を渡す。
- del文にDataFrameの列を渡す。
- dropに「columns=列名」を渡す。
- dropに「列名, axis=1」を渡す。
列col1を削除する方法を4通りで書いています。
列を削除したい場合はどれか一つの方法を実行していください。
1 2 3 4 5 6 7 8 9 10 11 |
#①popを使う方法 df.pop('col1') #②del文を使う方法 del df['col1'] #③dropで列を指定 df.drop(columns='col1', inplace=True) #➃dropで軸axisを指定 df.drop('col1', axis=1, inplace=True) |

- ③、➃のdropにある「inplace=True」は元のDataFrameを変更するという意味です。デフォルトではFalseになっているので、元のDataFrameは変更されません。
- axis=1で列、axis=0で行を指定します。
- inplaceやaxisなどのdropの引数の詳しい解説はコチラの記事にまとめています。
複数列を削除する
- del文に列をカンマ区切りで渡す。
- dropに列名をリストで指定する。
- dropの「列名のリスト, axis=1」を渡す。
- popは使えない。
1 2 3 4 5 6 7 8 |
#①del文に列をカンマ区切りで渡す。 del df['col1'], df['col2'] #②dropに列をリストで渡す。 df.drop(columns=['col1', 'col2'], inplace=True) #③dropの軸axisを指定する df.drop(['col1', 'col2'], axis=1, inplace=True) |

②、③のinplaceやaxisは上で説明した通りです。
詳しくは以下の記事にまとめています。
関連記事
こんにちは、今回はdrop関数に関して詳しくまとめていきたいと思います。 DataFrameの整形で非常に役に立つ関数なのでぜひ使い来ないしたいですね。 特に、dropを使ったのに削除できなかったときの対処法も書いています。 […]
行の削除
1行を削除する
- dropに行名を渡す。
- 行名の場合は軸axisなしでOK
- dropに「index=行名」を渡す。
1 2 3 4 5 |
#①行名を渡す。 df.drop('row1', inplace=True) #②indexに行名を渡す。 df.drop(index='row1', inplace=True) |

複数行を削除する
- dropに行名をリストで渡す。
- 行名の場合は軸axisなしでOK
- dropに「index=行名のリスト」を渡す。
1 2 3 4 5 |
#①行名のリストを渡す。 df.drop(['row1', 'row2'], inplace=True) #②indexに行名のリストを渡す。 df.drop(index=['row1', 'row2'], inplace=True) |

行と列を同時に削除する
- dropにindex(行名)とcolumns(列名)を指定
1 2 3 4 |
df.drop(index=['row1', 'row2'], columns='col2', inplace=True) df |

まとめ
いかがでしたか。
今回はDataFrameの行や列を削除する方法を紹介していきました。
細かい設定をしたい場合はdropでお手軽に削除したいならpopやdelでも十分対応可能ですね。