pandas.DataFrameで複数行・列を一括で削除する

スポンサーリンク

概要

  • pandas.DataFrameで複数の行や列をまとめて削除する方法
  • 削除したい行名・列名のリストを渡してdrop()で削除する

解決方法

準備

# DataFrameを準備
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randn(4, 4))
df.index = ['idx1', 'idx2', 'idx3', 'idx4']
df.columns = ['col1', 'col2', 'col3', 'col4']
# 出力結果
df

          col1      col2      col3      col4
idx1  0.660757  0.122939  0.450455  0.000483
idx2  1.948787  2.327604  0.626010 -0.092082
idx3  0.311708  0.926246 -0.083588  0.487964
idx4  0.284561 -0.076556  1.183666 -0.142197

削除したい行・列を指定する

drop_idx = ['idx2', 'idx3']
drop_col = ['col1', 'col4']

行を削除する

df.drop(drop_idx, axis=0)

# 出力結果
          col1      col2      col3      col4
idx1  0.660757  0.122939  0.450455  0.000483
idx4  0.284561 -0.076556  1.183666 -0.142197

列を削除する

df.drop(drop_col, axis=1)

# 出力結果
          col2      col3
idx1  0.122939  0.450455
idx2  2.327604  0.626010
idx3  0.926246 -0.083588
idx4 -0.076556  1.183666
スポンサーリンク