try: df.drop('b') except KeyError as ke: print(ke)
1 2 3 4 5 6 7
a b c d e 001234 156789 21011121314 31516171819 42021222324 "['b'] not found in axis"
上面的操作中出现了报错信息,什么原因?这是因为drop方法中,默认是删除行。
如果用axis=0或axis='rows',都表示展出行,也可用labels参数删除行。
1 2 3 4 5 6 7 8 9 10 11 12
df.drop(0) # drop a row, on axis 0 or 'rows' df.drop(0, axis=0) # same df.drop(0, axis='rows') # same df.drop(labels=0) # same df.drop(labels=[0]) # same
# 结果 a b c d e 156789 21011121314 31516171819 42021222324
如何删除列
如何删除列?可以指定axis或使用columns参数,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12
df.drop('b', axis=1) # drop a column df.drop('b', axis='columns') # same df.drop(columns='b') # same df.drop(columns=['b']) # same
# 输出 a c d e 00234 15789 210121314 315171819 420222324
classStupidFrameDelAttr(StupidFrameAttr): def__delattr__(self, item): # trivial implementation using the data model methods del self.__dict__['columns'][item]
f = StupidFrameDelAttr({'a': 1, 'b': 2, 'c': 3}) print("StupidFrameDelAttr value for a", f['a']) print("StupidFrameDelAttr columns: ", f.columns) del f['b'] print("StupidFrameDelAttr columns: ", f.columns) print("StupidFrameDelAttr value for a", f.a) f.d = 4 print("StupidFrameDelAttr columns: ", f.columns) del f.d print("StupidFrameDelAttr columns: ", f.columns)
# result StupidFrameDelAttr value for a 1 StupidFrameDelAttr columns: {'a': 1, 'b': 2, 'c': 3} StupidFrameDelAttr columns: {'a': 1, 'c': 3} StupidFrameDelAttr value for a 1 StupidFrameDelAttr columns: {'a': 1, 'c': 3, 'd': 4} StupidFrameDelAttr columns: {'a': 1, 'c': 3}