Drop multiple columns in pandas

PythonPandas

Python Problem Overview


I am trying to drop multiple columns (column 2 and 70 in my data set, indexed as 1 and 69 respectively) by index number in a pandas data frame with the following code:

df.drop([df.columns[[1, 69]]], axis=1, inplace=True)

I get the following error:

TypeError: unhashable type: 'Index'

And in my code the [1, 69] is highlighted and says:

Expected type 'Integral', got 'list[int]' instead

The following code does what I want it to do successfully, but on two lines of repetitive code (first dropping col index 69, then 1, and order does matter because dropping earlier columns changes the index of later columns). I thought I could specify more than one column index simply as a list, but perhaps I have something wrong above?

df.drop([df.columns[69]], axis=1, inplace=True)
df.drop([df.columns[1]], axis=1, inplace=True)

Is there a way that I can do this on one line similar to the first code snippet above?

Python Solutions


Solution 1 - Python

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Solution 2 - Python

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlukewitmerView Question on Stackoverflow
Solution 1 - PythonjorisView Answer on Stackoverflow
Solution 2 - PythonOkroshiashviliView Answer on Stackoverflow