python - 删除除具有特定条件的行之外的所有行

标签 python pandas

我想删除“文档编号”列中不包含“PD-19-05-16”或“PD-19-06-01”的所有行。但在我运行代码后,它似乎没有进行任何更改。

任何有关如何正确执行此操作或更正代码的建议将不胜感激。

我尝试使用 df.drop 但遇到了很多问题。

df = df.drop(['Document No.'] != ['PD-19-05-16','PD-19-06-01'])

我预计这会起作用,但得到了 ValueError: Arrays were different lengths: 4533 vs 2

最佳答案

尝试:

rows_to_keep = ["PD-19-05-16","PD-19-06-01"]
df.loc[df['Document No.'].isin(rows_to_keep)] 
#or if you need the inverse
df.loc[~df['Document No.'].isin(rows_to_keep)] 

我认为这不是 drop tbf 的正确用法。我总是发现使用 isin 来过滤单个列更容易。

~ 充当否定运算符

关于python - 删除除具有特定条件的行之外的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57313493/

相关文章:

python - 在列表理解中进行分配

python - 使用 BeautifulSoup 从 CSS 标签代码中提取信息

python - pandas groupby 删除列

python - 根据 csv 字段在数据框中创建列

python - 将单元格值与 Pandas 中的整数进行比较,给出类型错误

python - 扩展 Pandas 索引,其中新索引值为零

Python 强类型列表

python - 如何将 Mobilenium python 模块与 selenium 一起使用

Python 模块 ftplib FTP_TLS - 错误 530

python - 如何用其他数据框中的 id 替换数据框中的 2 列值?