The drop()
function in pandas removes the rows or columns of a DataFrame.
The drop()
function has the syntax shown below:
DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
The drop()
function takes the following parameter values:
labels
: This represents either the index label to remove a row or a column label to remove a column. It is equivalent to the index
parameter.axis
: This takes the axis of the DataFrame to drop. The value 0
is for the index
while 1
is for the column
.index
: This is equivalent to the labels
parameter.columns
: This takes the column label to be removed from the DataFrame.level
: This is used for multiIndex
DataFrame. It specifies the level from which the row of the DataFrame should be removed.inplace
: This takes a boolean value and specifies whether a copy of the result should be copied or not.errors
: This takes either ignore
or raise
as its values. If its value is set to ignore
, it avoids the error and returns a DataFrame whose existing labels are dropped.The drop()
function returns a DataFrame. If the parameter inplace
is set to True
, it returns None
.
# A code to illustrate the drop() function# importing required modulefrom pandas import DataFrame# creating a dataframemy_data_frame = DataFrame({'Id': [1, 2, 3, 4, 5, 6],'Name': ["Theo", "James", "John", "Peter", "Paul", "Hamed"] ,'Hieght(m)': [1.83, 1.98, 1.78, 1.8, 1.79, 2.0]})print(my_data_frame)print("\n")# dropping the "Id" and "Name" columnsprint(my_data_frame.drop(["Id", "Name"], axis = 1))# dropping the first and fifth rowsprint(my_data_frame.drop([0, 4]))
Dataframe
module from the pandas
library.my_data_frame
.my_data_frame
."Id"
and "Name"
by using the drop()
function. We print the result to the console.0
and 4
using the drop()
function. We print the result to the console.MultiIndex
DataFramefrom pandas import MultiIndex, DataFrame# creating a multiIndex dataframemy_multi_index = MultiIndex(levels=[['Tiger', 'Cow', 'Buffalo'],['Speed', 'Weight', 'Length']],codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],[0, 1, 2, 0, 1, 2, 0, 1, 2]])my_data_frame = DataFrame(index=my_multi_index, columns=['Big', 'Small'],data=[[45, 30], [200, 100], [1.5, 1], [30, 20],[250, 150], [1.5, 0.8], [320, 250],[1, 0.8], [0.3, 0.2]])print(my_data_frame)print("\n")# dropping a columnprint("Dropping the 'Big' Column")print(my_data_frame.drop(columns = ["Big"]))print("\n")# dropping a rowprint("Dropping the 'Tiger' Row")print(my_data_frame.drop(index = "Tiger"))
my_multi_index
and a MultiIndex DataFrame my_data_frame
.my_data_frame
.drop()
function, we drop the "Big"
column.drop()
function, we drop the "Tiger"
column.