如何在 Pandas 数据框中的特定列中搜索字符串值,如果存在,则给出数据框中该行的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44617996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to search a string value within a specific column in pandas dataframe, and if present, give an output of that row present in the dataframe?
提问by Devarshi Sengupta
I wish to search a database that I have in a .pkl file.
我希望搜索我在 .pkl 文件中拥有的数据库。
I have loaded the .pkl file and stored it in a variable named load_data.
我已加载 .pkl 文件并将其存储在名为 load_data 的变量中。
Now, I need to accept a string input using raw input and search for the string in one specific column 'SMILES
' of my dataset.
现在,我需要使用原始输入接受一个字符串输入,并在SMILES
我的数据集的一个特定列 ' ' 中搜索该字符串。
If the string matches, I need to display the whole row i.e all column values corresponding to that row.
如果字符串匹配,我需要显示整行,即与该行对应的所有列值。
Is that possible and if so, how should I go about it?
这可能吗,如果可以,我应该怎么做?
回答by jezrael
Use boolean indexing
that returns all matching rows:
使用boolean indexing
返回所有匹配的行:
df = pd.DataFrame({'a': [1,3,4],
'SMILES': ['a','dd b','f'],
'c': [1,2,0]})
print (df)
SMILES a c
0 a 1 1
1 dd b 3 2
2 f 4 0
If you need to check a string only:
如果您只需要检查一个字符串:
#raw_input for python 2, input for python 3
a = input('Enter String for SMILES columns: ') # f
#Enter String for SMILES columns: f
print (df[df['SMILES'] == a])
SMILES a c
2 f 4 0
Or if you need to check a sub string, use str.contains
:
或者,如果您需要检查子字符串,请使用str.contains
:
a = input('Enter String for SMILES columns: ') # b
print (df[df['SMILES'].str.contains(a)])
#Enter String for SMILES columns: b
SMILES a c
1 dd b 3 2