用法: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
|