How to Drop Multiple Columns in Python
In this article, let’s discuss how to drop multiple columns in Python. We are using Pandas Dataframe for demonstrating this.
First lets create a dummy dataframe.
import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5']} df = pd.DataFrame(data) df
Output:
A B C D E 0 a1 b1 c1 d1 e1 1 a2 b2 c2 d2 e2 2 a3 b3 c3 d3 e3 3 a4 b4 c4 d4 e4 4 a5 b5 c5 d5 e5
So now we’ve got the dataframe. We can use Pandas drop() function to drop multiple columns from a dataframe.
import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5']} df = pd.DataFrame(data) #remove columns with name 'A' and 'C' print(df.drop(['A', 'C'], axis = 1))
Output:
B D E 0 b1 d1 e1 1 b2 d2 e2 2 b3 d3 e3 3 b4 d4 e4 4 b5 d5 e5
We can also use Pandas drop() function without using axis=1 argument. However, we need to specify the argument “columns” with the list of column names to be dropped.
import pandas as pd data = { 'A':['a1', 'a2', 'a3', 'a4', 'a5'], 'B':['b1', 'b2', 'b3', 'b4', 'b5'], 'C':['c1', 'c2', 'c3', 'c4', 'c5'], 'D':['d1', 'd2', 'd3', 'd4', 'd5'], 'E':['e1', 'e2', 'e3', 'e4', 'e5']} df = pd.DataFrame(data) print(df.drop(columns = ['A', 'E']))
Output:
B C D 0 b1 c1 d1 1 b2 c2 d2 2 b3 c3 d3 3 b4 c4 d4 4 b5 c5 d5
Subscribe
Login
Please login to comment
0 Discussion