import pandas as pd
import numpy as np
#新建一个矩阵数据
df = pd.DataFrame(np.arange(20).reshape(4,5),columns=['A','B','C','D','E'])
In [23]:
df
Out[23]:
A | B | C | D | E | |
---|---|---|---|---|---|
0 | 0 | 1 | 2 | 3 | 4 |
1 | 5 | 6 | 7 | 8 | 9 |
2 | 10 | 11 | 12 | 13 | 14 |
3 | 15 | 16 | 17 | 18 | 19 |
删除一列=》给出列名+(axis=1)
In [24]:
df.drop('A',axis=1)
Out[24]:
B | C | D | E | |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
1 | 6 | 7 | 8 | 9 |
2 | 11 | 12 | 13 | 14 |
3 | 16 | 17 | 18 | 19 |
删除一行=》给出行名+(axis=0)
In [25]:
df.drop(1,axis=0)
Out[25]:
A | B | C | D | E | |
---|---|---|---|---|---|
0 | 0 | 1 | 2 | 3 | 4 |
2 | 10 | 11 | 12 | 13 | 14 |
3 | 15 | 16 | 17 | 18 | 19 |
当有columns时,不需要指定是列还是行
In [27]:
df.drop(columns=['C'])
Out[27]:
A | B | D | E | |
---|---|---|---|---|
0 | 0 | 1 | 3 | 4 |
1 | 5 | 6 | 8 | 9 |
2 | 10 | 11 | 13 | 14 |
3 | 15 | 16 | 18 | 19 |
当然删除行时,可以直接给出行号,不需要指定axis=0
In [28]:
df.drop(0)
Out[28]:
A | B | C | D | E | |
---|---|---|---|---|---|
1 | 5 | 6 | 7 | 8 | 9 |
2 | 10 | 11 | 12 | 13 | 14 |
3 | 15 | 16 | 17 | 18 | 19 |
In [34]:
midx = pd.MultiIndex(
levels=[
['lama', 'cow', 'falcon'],
['speed', 'weight', 'length']],
codes=[
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]])
df = pd.DataFrame(index=midx, columns=['big', 'small'],
data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
[250, 150], [1.5, 0.8], [320, 250],
[1, 0.8], [0.3,0.2]])
In [35]:
df
Out[35]:
big | small | ||
---|---|---|---|
lama | speed | 45.0 | 30.0 |
weight | 200.0 | 100.0 | |
length | 1.5 | 1.0 | |
cow | speed | 30.0 | 20.0 |
weight | 250.0 | 150.0 | |
length | 1.5 | 0.8 | |
falcon | speed | 320.0 | 250.0 |
weight | 1.0 | 0.8 | |
length | 0.3 | 0.2 |
In [36]:
df.drop(index='cow', columns='small')
Out[36]:
big | ||
---|---|---|
lama | speed | 45.0 |
weight | 200.0 | |
length | 1.5 | |
falcon | speed | 320.0 |
weight | 1.0 | |
length | 0.3 |