18

I have imported a Excel sheet into pandas. It has 7 columns which are numeric and 1 column which is a string (a flag).

After converting the flag to a categorical variable, I am trying to drop the string column from the Pandas dataframe. However, I am not able to do it.

Here's the code:

[In] parts_median_temp.columns

[Out] Index([u'PART_NBR', u'PRT_QTY', u'PRT_DOL', u'BTS_QTY', u'BTS_DOL', u'Median', u'Upper_Limit', u'Flag_median'], dtype='object')

The column I'm trying to drop is 'Flag_median'.

[In] parts_median_temp.drop('Flag_median') 

[Out] ...ValueError: labels ['Flag_median'] not contained in axis

Help me drop the Flag_median column from the Pandas dataframe.

Nick T
  • 25,754
  • 12
  • 83
  • 121
Learnerbeaver
  • 391
  • 2
  • 4
  • 12

2 Answers2

60

You have to use the inplace and axis parameter:

parts_median_temp.drop('Flag_median', axis=1, inplace=True)

The default value of 'inplace' is False, and axis' default is 0. axis=0 means dropping by index, whereas axis=1 will drop by column.

Chong Tang
  • 2,066
  • 15
  • 12
  • 1
    I wonder why this is not the correct answer. Because I tried [pandas](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html), but this is the one that worked for me. – akalanka Nov 27 '18 at 19:57
  • Or parts_median_temp.drop(columns='Flag_median', inplace=True) – JStrahl Apr 29 '20 at 08:46
4

You can try this:

parts_median_temp = parts_median_temp.drop('Flag_median', axis=1)
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
  • 1
    This hadnt worked. Had to include inplace=True to make it work. Thanks. – Learnerbeaver Jul 10 '16 at 04:14
  • 1
    @Learnerbeaver It works, you just have to change the dataframe so you put `parts_median_temp =` in front of the drop function. So, I edited my answer. I thought that was obvious. – Joe T. Boka Jul 10 '16 at 04:47