How to search for a word in excel using python pandas

Searching for a Word in Excel using Python Pandas

To search for a word in an Excel file using Python Pandas, you can follow the steps below:

  1. Import the required libraries:
  2.       
            import pandas as pd
          
        
  3. Read the Excel file into a Pandas DataFrame:
  4.       
            excel_file = 'path/to/excel/file.xlsx'
            df = pd.read_excel(excel_file)
          
        
  5. Create a Boolean mask for the desired word:
  6.       
            word = 'search_word'
            mask = df.apply(lambda row: row.astype(str).str.contains(word, case=False).any(), axis=1)
          
        
  7. Filter the DataFrame using the Boolean mask:
  8.       
            search_results = df[mask]
          
        
  9. View the search results:
  10.       
            print(search_results)
          
        

Here’s an example:

    
      import pandas as pd
      
      # Read the Excel file
      excel_file = 'data.xlsx'
      df = pd.read_excel(excel_file)
      
      # Word to search for
      word = 'apple'
      
      # Create a Boolean mask
      mask = df.apply(lambda row: row.astype(str).str.contains(word, case=False).any(), axis=1)
      
      # Filter the DataFrame
      search_results = df[mask]
      
      # View the search results
      print(search_results)
    
  

In this example, the code reads an Excel file named “data.xlsx” using Pandas. It then searches for the word “apple” in all the columns and returns the rows of the DataFrame that contain the word.

You can replace “data.xlsx” with the actual path to your Excel file and modify the word to search for according to your requirements.

Leave a comment