[英]Using Panda/Numpy to search matching string
我已經嘗試解決了一段時間了,但是還沒有解決。 我的目標是在名為“ WORDS”的列中搜索字符串並返回“ INDEXED_NUMBER”。 例如,如果我搜索了“ aaa”,它將返回我0,如下表所示。
我正在使用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筆記本作為補充說明。 我已經進口了熊貓和麻木。
提前致謝。 XD
將loc
與boolean indexing
一起使用,不要忘記添加return
to fuction,對於返回標量,也需要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
這是使用生成器實現算法的一種方法:
def WordToIndexwithjustPanda():
return next((i for i, j in zip(df['INDEXED_NUMBER', df['WORDS']) \
if 'aaa' in j), 'No match')
嚴格來說,它僅使用pandas的一部分,因為它使用了pd.Series
的迭代功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.