0

I have a dataframe with several columns:

df
pymnt_plan ... settlement_term days

Now I know which columns I Want to delete/drop, based on the following list:

    mylist = ['pymnt_plan',
     'recoveries',
     'collection_recovery_fee',
     'policy_code',
     'num_tl_120dpd_2m',
     'hardship_flag',
     'debt_settlement_flag_date',
     'settlement_status',
     'settlement_date',
     'settlement_amount',
     'settlement_percentage',
     'settlement_term']

How to drop multiple columns which their names in a list and assigned to a new dataframe? In this case:

df2
days
PV8
  • 5,799
  • 7
  • 43
  • 87
Leon
  • 389
  • 1
  • 4
  • 14
  • First of all, never use variable names with 'list'. l1 = ['col1','col1'...], `df = df.drop(l1, axis=1)` should work. – Scott Boston Jul 02 '18 at 16:12
  • It is dangerous to name a variable `list` with a lower-case `l` because you may have issues when you try to use the `list()` function later in your code. – BenG Jul 02 '18 at 16:17
  • @BenG-TWthanks for your advice – Leon Jul 02 '18 at 23:45
  • Possible duplicate of [Delete column from pandas DataFrame](https://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe) – PV8 Sep 30 '19 at 06:51
  • the solution you can also find here: https://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe?rq=1 – PV8 Sep 30 '19 at 06:51

2 Answers2

2

You can do

new_df = df[list]
df = df.drop(columns=list)
Zuma
  • 806
  • 1
  • 7
  • 10
  • 1
    While this should work, Pandas 0.20.3 gives: TypeError: drop() got an unexpected keyword argument 'columns' – Shawn Mar 18 '19 at 01:22
2

In Pandas 0.20.3 using 'df = df.drop(columns=list)' I get:

    TypeError: drop() got an unexpected keyword argument 'columns'

So you can use this instead:

    df = df.drop(axis=1, labels=list)
Shawn
  • 573
  • 3
  • 7
  • 17