-1

Hello guys I have been trying to drop 2 columns of Excel data frame on pandas, using a drop command like this

energy = energy.drop(energy.columns[[0 , 1]], axis= 1 )

however, I could not make it to avoid the columns from view. and finally i sense the columns I am supposed to delete comes as a multi level index on my machine. finally I have tried to drop one of the level from it like this

energy.index = energy.index.droplevel(2)

But still i cant manage to how I should avoid these columns.

I have attached a screen copy of my work enter image description here

Kyrubas
  • 877
  • 8
  • 23
Enqu T. Job
  • 21
  • 1
  • 5

4 Answers4

1

Instead of dropping the columns, you could subset your data frame like so:

In [3]: mydf = pd.DataFrame({"A":[1,2,3,4],"B":[4,3,2,1], "C":[3,4,5,3],"D":[6,4,3,2]})
In [4]: mydf
Out[4]:
   A  B  C  D
0  1  4  3  6
1  2  3  4  4
2  3  2  5  3
3  4  1  3  2
In [5]: mydf[mydf.columns[2:]]
Out[5]:
   C  D
0  3  6
1  4  4
2  5  3
3  3  2

This will work if you're trying to remove the first 2 columns for example. It works by creating a list with df.columns which you then subset and apply to your dataframe. You would then likely want to set the new dataframe to a variable. If the columns that you want to drop are nonadjacent you can loop through a list of columns to drop:

In [7]: mydf1 = mydf.copy()
In [8]: for col in ["A","D"]:
   ...:     mydf1 = mydf1.drop(col,axis=1)

In [9]: mydf1
Out[9]:
   B  C
0  4  3
1  3  4
2  2  5
3  1  3
Kyrubas
  • 877
  • 8
  • 23
1

Try simply renaming the columns

Say you have

In: df.columns 

Out: MultiIndex(levels=[['BURGLARY', 'GRAND LARCENY', 'GRAND LARCENY OF MOTOR 
     VEHICLE', 'TMAX', 'TMIN'], ['count', 'mean']],
     labels=[[0, 1, 2, 3, 4], [0, 0, 0, 1, 1]])

Then

In: df.columns = ['Burglary', 'Grand Larceny', 'Grand Larceny on Motor Vehicle', 
    'TMAX', 'TMIN']

And voila

In: df.columns

Out: Index(['BURGLARY', 'GRAND LARCENY', 'GRAND LARCENY OF MOTOR VEHICLE', 
     'TMAX',
     'TMIN'],
     dtype='object')
mberrett
  • 92
  • 6
0

If you really want to remove columns you can use del:

>>> df = pd.DataFrame({'A':range(3),'B':list('abc'), 'C':range(3,6), 'D':list('gde')})
>>> for x in ['A', 'B']:
...     del df[x]
... 
>>> df
   C  D
0  3  g
1  4  d
2  5  e
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
-1

This might help

energy.drop(energy.columns[[0,1]] , axis=1, inplace=True)
Jordfräs
  • 8,903
  • 3
  • 27
  • 30