gpt4 book ai didi

python - 使用 Panda/Numpy 搜索匹配字符串

转载 作者:行者123 更新时间:2023-12-01 02:05:48 25 4
gpt4 key购买 nike

我已经尝试解决这个问题有一段时间了,但还没有取得任何进展。我的目标是在名为“WORDS”的列中搜索字符串并返回“INDEXED_NUMBER”。例如,如果我搜索“aaa”,它应该返回 0,如下表所示。

Sample table

我正在使用 python panda,并且可能也在尝试 numpy。下面是我尝试过的代码示例:

def WordToIndexwithjustPanda():
referenceDF[referenceDF['WORDS'].str.contains('aaa')]
#I was hoping that it will grab me the row with the word 'aaa' but
#it is not returning me anything

def WordToIndexwithNumpy():
np.where(referenceDF["WORDS"].str.contains('aaa'))
#I think this is wrong but I am not sure how is this wrong

我希望你们能指导我正确的使用方法。我使用 anaconda 提示符和 jupyter 笔记本作为附加说明。我导入了 panda 和 numpy。

提前致谢。 XD

最佳答案

使用locboolean indexing并且不要忘记将 return 添加到函数中,对于返回标量也需要 iat 来使用 if-else< 选择过滤后的 Series 的第一个值 如果过滤不返回任何行:

def WordToIndexwithjustPanda():
a = referenceDF.loc[referenceDF['WORDS'].str.contains('aaa'), 'INDEXED_NUMBER']
return 'No match' if a.empty else a.iat[0]

您还可以在函数中使用参数来检查值的第一次出现:

referenceDF = pd.DataFrame({
'WORDS': ['aaa','aaas','aactive','aadvantage','aaker'],
'INDEXED_NUMBER': list(range(5))
})
print (referenceDF)
INDEXED_NUMBER WORDS
0 0 aaa
1 1 aaas
2 2 aactive
3 3 aadvantage
4 4 aaker

def WordToIndexwithjustPanda(val):
a = referenceDF.loc[referenceDF['WORDS'].str.contains(val), 'INDEXED_NUMBER']
return 'No match' if a.empty else a.iat[0]
print (WordToIndexwithjustPanda('aaa'))
0
print (WordToIndexwithjustPanda('bbb'))
No match

关于python - 使用 Panda/Numpy 搜索匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49086228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com