Python:当行元素由行名称中的字符串组成时删除行

Python: remove row when a row element consists of string within row name

我有数据框:

        Col1   Col2    
Rowab1   3     5
Rowbc2   4     6
Rowxy3   7     2

我想搜索数据框,只保留行名称包含 "bc" 的行,同时删除其余行:

        Col1   Col2
Rowab1   3     5
Rowxy3   7     2

我有如下一段代码:

df.loc[df.index.isin(['bc'])]

但是,这不会在字符串中搜索 "bc",而是搜索整个独立的字符串 "bc"。有没有我可以合并的 "like" 运算符,例如

df.loc[df.index.isin(['%bc%'])]  ?

谢谢!

您在 post 中说过您希望删除 不包含 "bc" 的每一行。这里有多种解决方案:

使用简单的字符串成员测试:

>>> df.ix[[i for i in df.index if 'bc' in i]]
        Col1  Col2
Rowbc2     4     6

使用正则表达式和 re 模块:

>>> df.ix[[i for i in df.index if re.match('.+bc.+', i)]]
        Col1  Col2
Rowbc2     4     6

您也可以使用 pandas.Series.str.match,正如我在评论中提到的:

>>> df[pd.Series(data=df.index, index=df.index).str.match('.+bc.+')]
        Col1  Col2
Rowbc2     4     6

您不能直接在 pandas.core.indexes.base.Index 对象上使用 pandas.Series.str.match,所以我只是将它转换为一个 pandas.Series 对象,并将有效垃圾作为值。您可以使用 Series 对象附带的 str 访问器。

pd.Series.str.find的替代方案:

In [41]: df
Out[41]: 
        Col1  Col2
Rowab1     3     5
Rowbc2     4     6
Rowxy3     7     2

In [42]: df[df.index.str.find('bc') > -1]
Out[42]: 
        Col1  Col2
Rowbc2     4     6