How to drop one or multiple columns from DataframePandas DataFrame is a two-dimensional labeled data structure with columns of potentially different data-types. Pandas DataFrame drop() method remove rows or columns by specifying label names and corresponding axis (0 for rows and 1 for columns.), or by specifying directly index or column names.
import pandas as pd import numpy as np df = pd.DataFrame() df['Name'] = ['John', 'Doe', 'Bill'] df['Promoted'] = [True, False,True] df['Marks'] = [82, 38, 63] df
Name Promoted Marks 0 John True 82 1 Doe False 38 2 Bill True 63
Drop column "Promoted"
df = df.drop('Promoted', 1) df
Name Marks 0 John 82 1 Doe 38 2 Bill 63where 1 is the axis number (0 for rows and 1 for columns.) In order to delete the column without having to reassign DataFrame you can do:
df.drop('column_name', axis=1, inplace=True)Please note that "inplace=True" was added in pandas v0.13 and it won't work on older versions.
Using Column NumberIf you want to drop by column number instead of by column label, try this to drop columns.
df = df.drop(df.columns[[0, 2]], axis=1)
Promoted 0 True 1 False 2 True
errors='ignore'errors='ignore' is the ability to drop columns only if they exist and it available from pandas 0.16.1 onward. This way you can cover more use cases, and when using errors='ignore' , it will only drop the existing columns from the labels passed to it.
df = df.drop('NotExist', axis=1)When you run this code, you will get the message KeyError: "['NotExist'] not found in axis" . If you use the argument errors='ignore' then drop() method will only drop the existing columns from the labels passed to it.
df = df.drop('NotExist', axis=1,errors='ignore')
- Creating an empty Pandas DataFrame
- How to Check if a Pandas DataFrame is Empty
- How to check if a column exists in Pandas Dataframe
- How to select multiple columns from Pandas DataFrame
- Selecting multiple columns in a Pandas dataframe based on condition
- Selecting rows in pandas DataFrame based on conditions
- How to Drop rows in DataFrame by conditions on column values
- Rename column in Pandas DataFrame
- Get a List of all Column Names in Pandas DataFrame
- How to add new columns to Pandas dataframe?
- Change the order of columns in Pandas dataframe
- Concatenate two columns into a single column in pandas dataframe
- How to count the number of rows and columns in a Pandas DataFrame
- Use a list of values to select rows from a pandas dataframe
- How to iterate over rows in a DataFrame in Pandas
- How to drop rows/columns of Pandas DataFrame whose value is NaN
- How to Export Pandas DataFrame to a CSV File
- Convert list of dictionaries to a pandas DataFrame
- How to set a particular cell value in pandas DataFrame