如何从 pandas 数据框中删除包含特定列中特定字符串的行? [英] How to drop rows from pandas data frame that contains a particular string in a particular column?

查看:103
本文介绍了如何从 pandas 数据框中删除包含特定列中特定字符串的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个非常大的数据框,我想在特定列中删除所有具有特定字符串的行.

I have a very large data frame in python and I want to drop all rows that have a particular string inside a particular column.

例如,我要在数据帧的C列中删除所有以字符串"XYZ"作为子字符串的行.

For example, I want to drop all rows which have the string "XYZ" as a substring in the column C of the data frame.

可以使用.drop()方法以有效的方式实现这一点吗?

Can this be implemented in an efficient way using .drop() method?

推荐答案

pandas具有向量化的字符串操作,因此您可以过滤掉包含不需要的字符串的行:

pandas has vectorized string operations, so you can just filter out the rows that contain the string you don't want:

In [91]: df = pd.DataFrame(dict(A=[5,3,5,6], C=["foo","bar","fooXYZbar", "bat"]))

In [92]: df
Out[92]:
   A          C
0  5        foo
1  3        bar
2  5  fooXYZbar
3  6        bat

In [93]: df[~df.C.str.contains("XYZ")]
Out[93]:
   A    C
0  5  foo
1  3  bar
3  6  bat

这篇关于如何从 pandas 数据框中删除包含特定列中特定字符串的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆