pandas删除 python

发布时间 2024-01-01 17:17:51作者: myrj
删除
删除有两种方法,一种是使用pop()函数。使用pop(),Series会删除指定索引的数据同时返回这个被删除的值,DataFrame会删除指定列并返回这个被删除的列。以上操作都是实时生效的。
# 删除索引为3的数据
s.pop(3)
# 93
s
'''
0 89
1 36
2 57
4 65
5 24
..
95 48
96 21
97 98
98 11
99 21
Name: Q1, Length: 99, dtype: int64
'''
# 删除Q1列
df.pop('Q1')
'''
0 89
1 36
2 57
3 93
4 65
..
100 88
101 88
103 88
104 88
105 88
Name: Q1, Length: 105, dtype: int64
'''
df
'''
name team Q2 Q3 Q4
0 Liver E 21 24 64
1 Arry C 37 37 57
2 Ack A 60 18 84
3 Eorge C 96 71 78
4 Oah D 49 61 86
.. ... ... .. .. ..
95 Gabriel C 59 87 74
96 Austin7 C 31 30 43
97 Lincoln4 C 93 1 20
98 Eli E 74 58 91
99 Ben E 43 41 74
[100 rows x 5 columns]
'''
还有一种方法是使用反选法,将需要的数据筛选出来赋值给原变量,最终实现删除。
5.4.12 删除空值
在一些情况下会删除有空值、缺失不全的数据,df.dropna可以执行这种操作:
df.dropna() # 一行中有一个缺失值就删除
df.dropna(axis='columns') # 只保留全有值的列
df.dropna(how='all') # 行或列全没值才删除
df.dropna(thresh=2) # 至少有两个空值时才删除
df.dropna(inplace=True) # 删除并使替换生效