Pandas DataFrameから列を削除する2つの方法

(1)DataFrameから1つの列を削除します。

df.drop('column name', axis=1, inplace=True)

(2)DataFrameから複数の列を削除します。

df.drop(['column 1', 'column 2', 'column 3', ...], axis=1, inplace=True)

簡単な例から始めるために、5 列の DataFrame を作成しましょう。

import pandas as pd

data = {'Color': ['Blue', 'Blue', 'Green', 'Green', 'Green', 'Red', 'Red', 'Red'],
        'Shape': ['Square', 'Square', 'Square', 'Rectangle', 'Rectangle', 'Rectangle', 'Square', 'Rectangle'],
        'Length': [15, 25, 25, 15, 15, 15, 20, 25],
        'Width': [8, 5, 5, 4, 8, 8, 5, 4],
        'Height': [30, 35, 35, 40, 30, 35, 40, 40]
        }

df = pd.DataFrame(data)

print(df)

Python でコードを実行すると、次の DataFrame が得られます。

Pandas DataFrame から列を削除する 1

以下のセクションでは、以下のドロップ方法について説明します。

  • DataFrameからの単一の列
  • DataFrameからの複数の列

Pandas DataFrame から単一の列を削除する

DataFrame から単一の列を削除するために使用できる方法は次のとおりです。

df.drop('column name', axis=1, inplace=True)

例えば、「Shape」列を削除してみましょう。これを行うには、次の構文を追加するだけです。

df.drop('Shape', axis=1, inplace=True)

したがって、「Shape」列を削除するための完全な Python コードは次のようになります。

import pandas as pd

data = {'Color': ['Blue', 'Blue', 'Green', 'Green', 'Green', 'Red', 'Red', 'Red'],
        'Shape': ['Square', 'Square', 'Square', 'Rectangle', 'Rectangle', 'Rectangle', 'Square', 'Rectangle'],
        'Length': [15, 25, 25, 15, 15, 15, 20, 25],
        'Width': [8, 5, 5, 4, 8, 8, 5, 4],
        'Height': [30, 35, 35, 40, 30, 35, 40, 40]
        }

df = pd.DataFrame(data)

df.drop('Shape', axis=1, inplace=True)

print(df)

ご覧のとおり、DataFrame には ‘Shape’ 列が存在しなくなりました。

Pandas DataFrame から列を削除する 2

Pandas DataFrame から単一の列を削除する

このテンプレートを使用して、DataFrame から複数の列を削除できます。

df.drop(['column 1', 'column 2', 'column 3', ...], axis=1, inplace=True)

たとえば、次の構文を追加して、Shape、Length、Width の列を削除してみましょう。

df.drop(['Shape', 'Length', 'Width'], axis=1, inplace=True)

したがって、3 つの列を削除する完全な Python コードは次のようになります。

import pandas as pd

data = {'Color': ['Blue', 'Blue', 'Green', 'Green', 'Green', 'Red', 'Red', 'Red'],
        'Shape': ['Square', 'Square', 'Square', 'Rectangle', 'Rectangle', 'Rectangle', 'Square', 'Rectangle'],
        'Length': [15, 25, 25, 15, 15, 15, 20, 25],
        'Width': [8, 5, 5, 4, 8, 8, 5, 4],
        'Height': [30, 35, 35, 40, 30, 35, 40, 40]
        }

df = pd.DataFrame(data)

df.drop(['Shape', 'Length', 'Width'], axis=1, inplace=True)

print(df)

これで、DataFrame に Shape、Length、Width の列がなくなったことがわかります。

Pandas DataFrame から列を削除する 3