亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查單元格內容是否存在于屏幕輸入的字符串中 - Python Pandas

檢查單元格內容是否存在于屏幕輸入的字符串中 - Python Pandas

三國紛爭 2022-08-16 18:23:27
我有一個包含2列的excel文件,如下所示。我想檢查列名“CODE1”中的單元格內容是否存在于從屏幕輸入的字符串中。然后在屏幕上返回結果是列名稱“結果”import pandas as pdimport getpassimport randompath_to_csv_file = 'C:\\names.xlsx'code_names_dataframe = pd.read_excel(path_to_csv_file) code_names_dictionary = code_names_dataframe.to_dict(orient='records')user_response = input()user_response=user_response.lower()while True:      name = None    username = user_response    for code_name in code_names_dictionary:        if username.contains(code_name['CODE1']).any():            name = code_name['RESULT']           if name is not None:            break           else:        print('Not Correct')        breakprint(name)      Excel 格式如下:CODE1       RESULTexcel       OK. Excelapple       OK. Apple我想當用戶在屏幕上輸入字符串為“我想收到一個蘋果”...然后結果將在屏幕上返回是“OK. 蘋果”當我運行代碼時,它顯示錯誤如下:Traceback (most recent call last):  File "C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelCSV.py", line 58, in <module>    mainmenu()  File "C:\Users\Administrator\Desktop\Chatbot - ReadData\ExcelCSV.py", line 49, in mainmenu    if username.contains(code_name['CODE1']).any():AttributeError: 'str' object has no attribute 'contains'
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

您可以將文本拆分為單詞列表,然后可以使用isin()


import pandas as pd


df = pd.DataFrame({

        'CODE': ['excel', 'apple'],

        'RESULT':['OK. Excel', 'OK. Apple']

})


text = 'I want to receive an apple'.lower()

words = text.split(' ')


mask = df['CODE'].isin(words)


print( mask )


print( df[ mask ] )


if mask.any():

    name = df[mask]['RESULT'].iloc[0]

else:

    name = None

print('Name:', name)  

結果


# mask

0    False

1     True

Name: CODE, dtype: bool


# df[mask]    

    CODE     RESULT

1  apple  OK. Apple


Name: OK. Apple

編輯:其他方法


mask = df['CODE'].apply(lambda x: x.lower() in text.lower())

法典


import pandas as pd


df = pd.DataFrame({

        'CODE': ['excel file', 'apple'],

        'RESULT':['OK. Excel', 'OK. Apple']

})


text = 'I have excel file on the PC'


mask = df['CODE'].apply(lambda x: x.lower() in text.lower())


print( mask )


print( df[ mask ] )


if mask.any():

    name = df[mask]['RESULT'].iloc[0]

else:

    name = None

print('Name:', name) 

結果


# mask

0     True

1    False

Name: CODE, dtype: bool


# df[mask]

         CODE     RESULT

0  excel file  OK. Excel


Name: OK. Excel


查看完整回答
反對 回復 2022-08-16
  • 1 回答
  • 0 關注
  • 78 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號