Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to drop a column from pandas dataframe [duplicate]

Tags:

python

pandas

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.

like image 310
Learnerbeaver Avatar asked Jul 10 '16 03:07

Learnerbeaver


People also ask

Why drop duplicates pandas not working?

If the date data is a pandas object dtype, the drop_duplicates will not work - do a pd. to_datetime first.

How do I get rid of duplicate columns in pandas?

To drop duplicate columns from pandas DataFrame use df. T. drop_duplicates(). T , this removes all columns that have the same data regardless of column names.

How do I drop a column in a Pandas DataFrame?

During the data analysis operation on a dataframe, you may need to drop a column in Pandas. You can drop column in pandas dataframe using the df. drop(“column_name”, axis=1, inplace=True) statement.


2 Answers

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.

like image 96
Chong Tang Avatar answered Oct 15 '22 00:10

Chong Tang


You can try this:

parts_median_temp = parts_median_temp.drop('Flag_median', axis=1)
like image 23
Joe T. Boka Avatar answered Oct 15 '22 00:10

Joe T. Boka