A data frame in pandas is a dataset that combined rows and columns. We need to understand and learn about various methods available in Pandas in order to do the preprocessing of the dataset. Sometimes, we need to add or delete rows and columns from the dataset. In this case, we will learn how to delete a column in Pandas using different methods.
Delete a Column in Pandas
The popular method used to delete a column from the Pandas data frame is drop() method. While using this method, we need to specify the axis of dropping because by default the axis of dropping is the row, not the column.
Let us import a dataset and then drop the column from it using the drop() method:
# importing the module import pandas as pd # dataset data = pd.read_csv('Dushanbe_house.csv') data.head()
Now we will use the drop method to delete the column from the dataset:
Delete a Single Column
To delete or drop a single column from the data frame, we can use the drop() method as shown below:
# dropping column data.drop('Unnamed: 0', axis=1)
This will drop the column from the data frame for the moment. If you will print the data again, you will notice that the column is still there. In order to delete the column permanently from the dataset, we need to specify it explicitly in the parameter.
# dropping column data.drop('Unnamed: 0', axis=1, inplace=True)
The inplace=True means that we want to drop the column completely from the dataset.
inplace=True means that we want to drop the column completely from the dataset.
Delete Multiple Columns in Pandas
The drop() in pandas can also be used to delete multiple columns from the Pandas data frame. We need to specify all the columns that we want to drop from our data frame.
# dropping column data.drop(['floor', 'area', 'price'], axis=1, inplace=True)
As you can see, now we have only a few columns left as we deleted multiple columns using the drop method.
The drop() method in pandas is used to drop single and multiple columns from the data frame. We need to specify the axis of drop and the axis for column is 1. If we want to drop the column permanently, then we need to specify the inplace parameter value as well.
- How to Change Font Size in Matplotlib?
- How to Delete Cell in Jupyter Notebook?
- How to Calculate Entropy in Decision Tree?