Explore Courses Blog Tutorials Interview Questions
+3 votes
in Python by (3.9k points)
edited by

How to delete a column in a DataFrame, currently I am using:

del df['column_1']

this is working fine, but I tried this:

del df.column_1

this command isn't working as expected df.column_name ?

3 Answers

0 votes
by (2k points)
edited by

Use drop to perform this task:

columns = ['Col1', 'Col2', ... , 'ColN']
df.drop(columns, inplace=True, axis=1)
Here 'N' belongs to a positive integer 

+4 votes
by (10.9k points)

You can use pop() method to delete a column name:



+1 vote
by (106k points)
edited by

Actually, the proper way to delete a column from pandas data frame is same what you've guessed:-

del df['column_name']

But It is very difficult to make del df.column_name work simply as the result of syntactic limitations in Python. del df[name] gets translated to df.__delitem__(name) under the covers by Python.

If you want to try an alternate way of deleting the column in pandas is to use the drop():-

df = df.drop('column_name', 1)

Here 1 is the axis number which is 0 for rows and 1 for columns.

You can use the following video tutorials to clear all your doubts:-

Related questions

Browse Categories