LoginSignup
31
34

More than 5 years have passed since last update.

【Python】DataFrameで複数行・列をまとめて削除する

Last updated at Posted at 2016-07-04

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
31
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
34