pandas删除数据主要有两种方式:
1.在dataframe上调用drop、dropna、drop_duplicates函数
2.通过切片找到相应的行或列,然后使用 del 命令删除
1、del
del只能删除列,并且一次只能删一列,并且del只能删除[]运算符切片的列
import pandas as pd
scores = [23, 88, 12], [99, 88, 100], [44, 77, 68]
df = pd.DataFrame(scores, index=['张三', '李四', '王二麻子'], columns=['语文', '数学', '英语'])
del df[["英语", "数学"]] # InvalidIndexError
del df["英语"] # del success
del df.iloc[:, 0] # AttributeError: __delitem__
del df.loc[:, "语文"] # AttributeError: __delitem__
2、dropna
删除存在缺失值的行或列
def dropna(self,
*,
axis: Literal["index", "columns", "rows"] | int = 0,
how: Literal["any", "all"] | _NoDefault = no_default,
thresh: int | _NoDefault = no_default,
subset: Hashable | Sequence[Hashable] | None = None,
inplace: bool = False,
ignore_index: bool = False)
axis:
· 0、"rows"、"index" - 删除存在无效值的行
· 1、"columns" - 删除存在无效值的列
default: 0
how:
· "any" - 只要有一个无效值就删除该行/列
· "all" - 整行/列全都是无效值才删除该行/列
default: no_default , 但是其实效果等同于"any"
thresh:
· 整数值 - 指定有多少个有效值该行列就不会被删除,thresh和how不能同时设置!!!
比如如果设置thresh=1,那么只要该行/列有一个有效值,该行/列就不会被删除
subset:
· 要考虑的其他轴上的标签,例如,如果要删除行,那么这个参数可以是columns的一个子集,然后只会
在subset指定的列中寻找无效值
inplace:
· 标志是原地修改df(True)还是返回一个新的df(False)
ignore_index:
· 是否忽略df的行标签(index),如果为True,则df的index会被置为从0开始的整数值
这个没什么必要展示代码了,只要清楚参数怎么用就行了,有一点要注意:thresh和subset配合时要注意,如果thresh>len(subset),会导致有效值不足,最终得到一个空dataframe。
3、drop_duplicates
删除重复的行
def drop_duplicates(self,
subset: Hashable | Sequence[Hashable] | None = None,
*,
keep: Literal["first", "last", False] = "first",
inplace: bool = False,
ignore_index: bool = False)
subset:
· 比较重复值的列,默认是比较所有的列
keep:
· "first" - 有重复行时保留第一行
· "last" - 有重复行时保留最后一行
· False - 有重复行时把重复行全部删除
inplace:
· 标志是原地修改df(True)还是返回一个新的df(False)
ignore_index:
· 是否忽略df的行标签(index),如果为True,则df的index会被置为从0开始的整数值
4、drop
删除指定的行/列
def drop(self,
labels: Hashable | Sequence[Hashable] | None = None,
*,
axis: Literal["index", "columns", "rows"] | int = 0,
index: Hashable | Sequence[Hashable] | None = None,
columns: Hashable | Sequence[Hashable] | None = None,
level: Hashable | None = None,
inplace: bool = False,
errors: Literal["ignore", "raise"] = "raise")
labels+axis = index | columns
就是说:设置labels+axis(0) 和设置index的效果是一样的
设置labels+axis(1) 和设置columns的效果是一样的
level 是给MultiIndex用的,dataframe和series用不上
errors - 删除失败是抛出异常还是什么都不做
import pandas as pd
scores = [23, 88, 12], [99, 88, 100], [44, 77, 68], [44, 77, 68]
df = pd.DataFrame(scores, index=['张三', '李四', '王五', "赵六"], columns=['语文', '数学', '英语'])
# 删除学生赵六的成绩
df.drop(labels="赵六", inplace=True)
=
df.drop(index="赵六", inplace=True)
# 英语取消了,删除所有学生的英语成绩
df.drop(labels="英语", axis=1, inplace=True)
=
df.drop(columns="英语", inplace=True)