我有数据框:
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%'])] ?
谢谢!
最佳答案
替代方案 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
关于Python:当行元素由行名称中的字符串组成时删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961156/