深度阅读

How to drop one or multiple columns in Pandas Dataframe

作者
作者
2023年08月22日
更新时间
10.25 分钟
阅读时间
0
阅读量

To drop one or multiple columns in a Pandas dataframe, you can use the drop() method. Here are some examples:

To drop a single column:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df = df.drop('B', axis=1)

print(df)

Output:

   A  C
0  1  7
1  2  8
2  3  9

To drop multiple columns:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df = df.drop(['B', 'C'], axis=1)

print(df)

Output:

   A
0  1
1  2
2  3

In both cases, axis=1 specifies that we want to drop columns, and the column label or list of labels to be dropped is passed as the first argument to drop().

If you want to modify the original dataframe instead of creating a new one, you can set the inplace parameter to True:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
df.drop('B', axis=1, inplace=True)

print(df)

Output:

   A  C
0  1  7
1  2  8
2  3  9

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。