Home > Backend Development > Python Tutorial > Why Doesn't `del df.column_name` Work for Deleting Pandas DataFrame Columns?

Why Doesn't `del df.column_name` Work for Deleting Pandas DataFrame Columns?

Mary-Kate Olsen
Release: 2024-12-11 01:15:09
Original
343 people have browsed it

Why Doesn't `del df.column_name` Work for Deleting Pandas DataFrame Columns?

Deleting Columns from Pandas DataFrames: del vs. drop()

In Pandas, deleting columns from a DataFrame can seem straightforward. However, why doesn't the syntax del df.column_name work as anticipated?

While it's possible to access Series via df.column_name, attempting to delete the column using del df.column_name fails. The proper method for column deletion is through the drop() function.

To delete a column using drop(), specify the column name and set the axis argument to 1 (for columns). Alternatively, use the columns keyword to specify the columns to be dropped. For example:

df = df.drop('column_name', axis=1)  # Old syntax
df = df.drop(columns='column_name')  # New syntax
Copy after login

To perform column deletion without reassigning the DataFrame, use inplace=True as follows:

df.drop('column_name', axis=1, inplace=True)
Copy after login

Additionally, columns can be dropped by number using the axis=1 argument and indexing the df.columns object. To drop columns 1, 2, and 4 (zero-based indexing), do the following:

df.columns[[0, 1, 3]]  # Select columns to drop
df = df.drop(df.columns[[0, 1, 3]], axis=1)
Copy after login

The above is the detailed content of Why Doesn't `del df.column_name` Work for Deleting Pandas DataFrame Columns?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template