用法:DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)
参数说明:
labels 就是要删除的行列的名字,用列表给定
axis 默认为0,指删除行,因此删除columns时要指定axis=1;
index 直接指定要删除的行
columns 直接指定要删除的列
inplace=False,默认该删除操作不改变原数据,而是返回一个执行删除操作后的新dataframe;
inplace=True,则会直接在原数据上进行删除操作,删除后无法返回。
因此,删除行列有两种方式:
1)labels=None,axis=0 的组合
2)index或columns直接指定要删除的行或列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
>>>df
=
pd.DataFrame(np.arange(
12
).reshape(
3
,
4
), columns
=
[
'A'
,
'B'
,
'C'
,
'D'
])
>>>df
A B C D
0
0
1
2
3
1
4
5
6
7
2
8
9
10
11
#Drop columns,两种方法等价
>>>df.drop([
'B'
,
'C'
], axis
=
1
)
A D
0
0
3
1
4
7
2
8
11
>>>df.drop(columns
=
[
'B'
,
'C'
])
A D
0
0
3
1
4
7
2
8
11
# 第一种方法下删除column一定要指定axis=1,否则会报错
>>> df.drop([
'B'
,
'C'
])
ValueError: labels [
'B'
'C'
]
not
contained
in
axis
#Drop rows
>>>df.drop([
0
,
1
])
A B C D
2
8
9
10
11
>>> df.drop(index
=
[
0
,
1
])
A B C D
2
8
9
10
11
|
- 删除指定的行呢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
>>>
import
pandas as pd
>>> df
=
{
'DataBase'
:[
'mysql'
,
'test'
,
'test'
,
'test'
,
'test'
],
'table'
:[
'user'
,
'student'
,
'course'
,
'sc'
,
'book'
]}
>>> df
=
pd.DataFrame(df)
>>> df
DataBase table
0
mysql user
1
test student
2
test course
3
test sc
4
test book
#删除table值为sc的那一行
>>> df.drop(index
=
(df.loc[(df[
'table'
]
=
=
'sc'
)].index))
DataBase table
0
mysql user
1
test student
2
test course
4
test book
|
1
2
3
4
5
|
#多行也可以哦
>>> df.drop(index
=
(df.loc[(df[
'DataBase'
]
=
=
'test'
)].index))
DataBase table
0
mysql user
|