使用drop()方法从pandas DataFrame中删除列

时间:2018-06-24 14:11:07

标签: python python-3.x pandas numpy dataframe

我查找了“使用del df.column_name从pandas DataFrame删除列”问题的答案。在那里我看到人们更喜欢drop()方法而不是del df.column,因为您可以删除多列。无论如何,当我使用drop()方法时,我遇到了麻烦并收到错误消息。以下是我编写的代码:

import numpy as np
import pandas as pd 
#install xlrd
!pip install xlrd
print('xlrd installed!') 
df_can=pd.read_excel('https://ibm.box.com/shared/static /lw190pt9zpy5bd1ptyg2aw15awomz9pu.xlsx',
                   sheet_name='Canada by Citizenship',skiprows=range(20),
                   skipfooter=2
                  )

print('Data downloaded and read into dataframe')
df_can.head(10)
print(df_can.shape)
#Drop the columns (axis=1) which are not useful to us for visualization.
cols=['Type','Coverage','AREA','REG','DEV']
df_can.drop(cols,axis=1,inplace=True)
df_can.head()

运行代码时,出现以下错误消息:


KeyError                                  Traceback (most recent call  last)
<ipython-input-19-f9b9a9fefc0e> in <module>()
  1 #Drop the columns (axis=1) which are not useful to us for visualization.
  2 cols=['Type','Coverage','AREA','REG','DEV']
----> 3 df_can.drop(cols,axis=1,inplace=True)
  4 df_can.head()

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in drop(self, labels, axis, index, columns, level, inplace, errors)
 3692                                            index=index,   columns=columns,
 3693                                            level=level,  inplace=inplace,
-> 3694                                            errors=errors)
 3695 
 3696     @rewrite_axis_style_signature('mapper', [('copy', True),

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in  drop(self, labels, axis, index, columns, level, inplace, errors)
3106         for axis, labels in axes.items():
3107             if labels is not None:
-> 3108                 obj = obj._drop_axis(labels, axis, level=level, errors=errors)
3109 
3110         if inplace:

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in _drop_axis(self, labels, axis, level, errors)
3138                 new_axis = axis.drop(labels, level=level, errors=errors)
3139             else:
-> 3140                 new_axis = axis.drop(labels, errors=errors)
3141             dropped = self.reindex(**{axis_name: new_axis})
3142             try:

~/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in drop(self, labels, errors)
4385             if errors != 'ignore':
4386                 raise KeyError(
-> 4387                     'labels %s not contained in axis' % labels[mask])
4388             indexer = indexer[~mask]
4389         return self.delete(indexer)

KeyError: "labels ['Type' 'Coverage' 'AREA' 'REG' 'DEV'] not contained in axis"

0 个答案:

没有答案