我们先来看看DataFrame.drop的帮助文档:
Help on function drop in module pandas.core.frame:
drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level.
Parameters ----------
labels : single label or list-like Index or column labels to drop. axis : {0 or 'index', 1 or 'columns'}, default 0 Whether to drop labels from the index (0 or 'index') or columns (1 or 'columns').
index, columns : single label or list-like Alternative to specifying axis (``labels, axis=1`` is equivalent to ``columns=labels``).
..versionadded::0.21.0
level : int or level name, optional For MultiIndex, level from which the labels will be removed.
inplace : bool, default False If True, do operation inplace and return None.
errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and only existing labels are dropped.
Returns ------- dropped : pandas.DataFrame
先创建一个DataFrame对象,为方便演示,我创建了一个索引既有时间,也有其他类型的索引。
In[1]: import pandas as pd
In[2]: df = pd.DataFrame([11, 12, 13, 14, 15, 16, 17], index = [0, 1, 2, '2018-01-01', '2018-01-02', 'a', 'b'], columns = ['V'])
In[3]: print(df)
Out[3]:
V
0 11
1 12
2 13
2018-01-01 14
2018-01-02 15
a 16
b 17
通过帮助文档我们简单了解到一个重要参数inplace=False,这个参数控制着DataFrame.drop的操作是在原DataFrame删除还是不在原DataFrame上删除,默认不在原DataFrame上操作。
labels参数
DataFrame.drop()中的参数labels是要删除的行或者列的名字,删除行还是列由参数axis控制,axis默认为0即按行删除,要想删除列只需令axis=1。
In[4]: df.drop([2,'2018-01-01','a'])
Out[4]:
V
0 11
1 12
2018-01-02 15
b 17
如果要删除列‘V’,只需如下操作:
In[5]: df.drop(['V'],axis=1)
Out[5]:
0
1
2
2018-01-01
2018-01-02
a
b
index参数
对于参数index,这个参数只能传入行的名字即它是专为按行删除设置的,axis的值不影响index,axis的值只在给labels传入参数时起作用。
In[6]: df.drop(index = 'a',axis = 1)
Out[6]:
V
0 11
1 12
2 13
2018-01-01 14
2018-01-02 15
b 17
columns参数的用法与index的用法是类似的。
level参数目前我还没用过,用到了再说了。
errors参数控制着当labels接收到没有的行名或者列名时,程序应该执行的操作。
errors='raise'会让程序在labels接收到没有的行名或者列名时抛出错误导致程序停止运行,errors='ignore'会忽略没有的行名或者列名,只对存在的行名或者列名进行操作。
想要了解更加详细信息,自己在python中用help(pd.DataFrame.drop)或者参阅:DataFrame.drop
网友评论