Home > Net >  Want to drop multiple col iterating over a list in python
Want to drop multiple col iterating over a list in python

Time:10-25

listDemo = list('gender', 'tenture')
dfDemo = df

for col in listDemo:
    dfDemo = dfDemo.drop[[col],  inplace=True, axis=1]

dfDemo.head(2)

I am getting Syntax Error, can anyone help please...

CodePudding user response:

Try:

dfDemo = dfDemo.drop([col],  inplace=True, axis=1)

CodePudding user response:

Firstly, while creating list you'd need to pass a single argument (tuple in the below code).
Second, when you use inplace=True the drop statement returns None. So, df.head(2) wouldn't return anything anyway.
Third, you need to use parentheses when using a method/function.

Check if below code works fine:

listDemo = list(('gender', 'tenture'))
dfDemo = df

for col in listDemo:
    dfDemo.drop(col,  inplace=True, axis=1)

dfDemo.head(2)

You can also drop all the columns from listDemo in one go without using a loop:

dfDemo.drop(listDemo,  inplace=True, axis=1)
  • Related