深度阅读

How to Drop Columns in Pandas

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

To drop a column in a Pandas DataFrame, you can use the drop() method. Here’s an example:

import pandas as pd

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

# drop column 'B' from the dataframe
df = df.drop('B', axis=1)

# print the resulting dataframe
print(df)

In this example, we first create a Pandas DataFrame with three columns (‘A’, ‘B’, and ‘C’) and three rows. We then use the drop() method to remove the ‘B’ column from the dataframe. The axis=1 argument specifies that we want to drop the column axis, rather than the row axis. Finally, we print out the resulting dataframe to confirm that the column has been dropped.

Note that the drop() method returns a new DataFrame with the specified column removed - if you want to modify the original dataframe in place, you can use the inplace=True argument:

# drop column 'B' from the dataframe in place
df.drop('B', axis=1, inplace=True)

# print the resulting dataframe
print(df)

This code will have the same effect as the previous example, but the original dataframe will be modified rather than creating a new one.

相关标签

博客作者

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