Как извлечь столбец электронной почты из файла Excel и узнать тип почты с помощью Pandas?
В этой статье давайте посмотрим, как извлечь столбец электронной почты из файла Excel и узнать тип почты с помощью Pandas. Предположим, что наш файл Excel выглядит так, как показано на рисунке ниже, а затем нам нужно хранить разные типы электронных писем в разных столбцах Dataframe.

Для просмотра файла Excel нажмите здесь
Подход:
- Import required module.
- Import data from Excel file.
- Make an extra column for each different Email.
- Set Each required Index for searching.
- Define the Pattern of the Email.
- Search the Email and assigning to the respective column in Dataframe.
Давайте посмотрим на пошаговую реализацию:
Step 1: Import the required module and read data from Excel file.
Python3
# import required moduleimport pandas as pd;import re; # Read excel file and store in to DataFramedata = pd.read_excel("Email_sample.xlsx"); # show the dataframedata |
Выход:

Step 2: Make an extra column for each different Email.
Python3
data["Google-mail"] = None data |
Выход:

Python3
data["Yahoo-mail"] = Nonedata |
Выход :

Step 3: Set Each required Index for searching.
Python3
# set required index index_set = data.columns.get_loc("E-mail")index_gmail = data.columns.get_loc("Google-mail")index_yahoo = data.columns.get_loc("Yahoo-mail") print(index_set, index_gmail, index_yahoo) |
Выход:
1 2 3
Step 4: Defining the Pattern of the Email.
Python3
# define pattern of Emailgoogle_pattern = r"gmail.com"yahoo_pattern = r"yahoo.com" |
Step 5: Searching the Email and assigning into respective column in Dataframe.
Python3
# Search the Email in DataFrame and store for row in range(0, len(data)): if re.search(google_pattern, data.iat[row, index_set]) == None : data.iat[row,index_gmail] = "Account not belongs to Google" else: gmail = re.search(google_pattern, data.iat[row, index_set]).group() data.iat[row,index_gmail] = "Google-Mail" if re.search(yahoo_pattern, data.iat[row, index_set]) == None : data.iat[row,index_yahoo] = "Account not belongs to Yahoo" else: yahoo = re.search(yahoo_pattern, data.iat[row, index_set]).group() data.iat[row,index_yahoo] = "Yahoo-Mail" data |
Выход:

Complete Code:
Python3
# importing required moduleimport pandas as pdimport re # Creating df# Reading data from Exceldata = pd.read_excel("Email_sample.xlsx")print("Original DataFrame")print(data) # Create column for# each type of Emaildata["Google-mail"] = Nonedata["Yahoo-mail"] = None # set indexindex_set = data.columns.get_loc("E-mail")index_gmail = data.columns.get_loc("Google-mail")index_yahoo = data.columns.get_loc("Yahoo-mail") # define Email patterngoogle_pattern = r"gmail.com"yahoo_pattern = r"yahoo.com" # Searching the email# Store into DataFramefor row in range(0, len(data)): if re.search(google_pattern, data.iat[row, index_set]) == None: data.iat[row, index_gmail] = "Account not belongs to Google" else: gmail = re.search(google_pattern, data.iat[row, index_set]).group() data.iat[row, index_gmail] = "Google-Mail" if re.search(yahoo_pattern, data.iat[row, index_set]) == None: data.iat[row, index_yahoo] = "Account not belongs to Yahoo" else: yahoo = re.search(yahoo_pattern, data.iat[row, index_set]).group() data.iat[row, index_yahoo] = "Yahoo-Mail" data |
Выход :

Примечание. Перед запуском этой программы убедитесь, что вы уже установили библиотеку xlrd в среде Python.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.