python - 如何创建一个函数来接受 pandas 数据框并删除包含特定值的行?

标签 python python-3.x pandas function dataframe

我希望创建一个函数,它将接受一个 pandas 数据框和一个特定值 (to_drop),然后它将删除包含指定值的任何行。

例如,如果我有这个数据框:

d = {'Name': ['John', 'Bill', "Frank"], 'A' : [1, 5, 7], 'B': [2, 0, 6], 'C' : [3, 1, 9]}
df = pd.DataFrame(d)

如果我选择的具体值为 0,函数应该删除 Bill 的行,返回 John 和 Frank 的行。

我正在尝试使用:

def drop_row(df, to_drop):
    new_df = df[df.column != to_drop]
    return new_df

这会导致属性错误,我认为这是因为这仅在您选择特定列时有效。

谢谢!

最佳答案

使用pandas.DataFrame.anypandas.DataFrame.all沿 axis=1 条件:

>>> df[df.ne(0).all(1)]
    Name  A  B  C
0   John  1  2  3
2  Frank  7  6  9

>>> df[~df.eq(0).any(1)]
    Name  A  B  C
0   John  1  2  3
2  Frank  7  6  9

你可以用它做一个函数,但坦率地说,这是不必要的:

>>> drop_row = lambda df: df[~df.eq(0).any(1)]
>>> drop_row(df)
    Name  A  B  C
0   John  1  2  3
2  Frank  7  6  9

它检查条件:

>>> df.ne(0) # items (n)ot (e)qual to 0:
   Name     A      B     C
0  True  True   True  True
1  True  True  False  True
2  True  True   True  True

>>> df.ne(0).all(1)  # checks if all values along axis 1 are True
0     True
1    False
2     True
dtype: bool

>>> df[df.ne(0).all(1)]  # Returns only index where values is True (i.e. 0, 2)
    Name  A  B  C
0   John  1  2  3
2  Frank  7  6  9

关于python - 如何创建一个函数来接受 pandas 数据框并删除包含特定值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66091152/

相关文章:

python - 当数据帧包含混合数据类型时,Pyarrow from_pandas 会使解释器崩溃

python - 在 Python 中解析大型 XML 文件

python-3.x - mprof run <executable> 让我得到 "Command not found"

python - 如何从 Pandas 中的 DatetimeIndex 获取滚动窗口内的持续时间

python - 使用 pandas 进行插值时如何控制 X 和 Y

python - 检查索引 Pandas 中是否包含数字的问题

Python错误: Couldn't read from RWops

python - Matplotlib 根据值使用不同颜色填充区域

mysql - 比较peewee sql Python中的日期时间

python - pyqt QStandardItemModel 有没有办法从模型中完全删除值?