简体   繁体   English

如何使用 pandas 编写 python 脚本来迭代具有多张工作表的 Excel.xlsx 文件?

[英]How can I write a python scripts using pandas to iterate over Excel .xlsx files with multiple sheets?

I have some Excel.Xlsx files.我有一些 Excel.Xlsx 文件。 Each file contains multiple sheets.每个文件包含多张工作表。 I have used the following code to read and extract data from the files:我使用以下代码从文件中读取和提取数据:

import pandas as pd
file = pd.ExcelFile('my_file.xlsx')
file.sheet_names #Displays the sheet names
df = file.parse('Sheet1') #To parse Sheet1
df.columns #To list columns

My interest is the email columns in each sheet.我感兴趣的是每张纸中的 email 列。 I have been doing this almost manually with the code above.我一直在使用上面的代码几乎手动执行此操作。 I need a code to automatically iterate over the sheets and extract all emails.我需要一个代码来自动遍历工作表并提取所有电子邮件。 Help!帮助!

You can pass over all files and all sheets with a for loop:您可以使用 for 循环传递所有文件和所有工作表:

import pandas as pd
import os

emails = []
files_dir = "/your_path_to_the_xlsx_files"
for file in os.listdir(files_dir):
    excel = pd.ExcelFile(os.path.join(files_dir,file))
    for sheet in excel.sheet_names:
        df = excel.parse(sheet)
        if 'email' not in df.columns:
            continue
        emails.extend(df['email'].tolist())

Now you have all the emails in the emails list.现在您拥有电子邮件列表中的所有电子邮件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要使用 python 中的 pandas 拆分 csv 数据库中的数据,并将其写入具有多张工作表的 xlsx 文件,并创建一个额外的 col - I need to split data in a csv database using pandas in python and write it to and xlsx file with multiple sheets as well as creating an additional col 使用python pandas在excel中的多个工作表中写入数据 - Write data in multiple sheets in excel using python pandas 如何使用Python Pandas将CSV文件写入XLSX? - How to write CSV files into XLSX using Python Pandas? 如何将Python数据框写入多个Excel文件的多个表 - How to write Python dataframe to multiple sheets of multiple Excel files 如何遍历 excel 文件表并在 Python 中插入公式? - How can I iterate through excel files sheets and insert formula in Python? 如何使用 openpyxl 和 python 在 excel 中写入多张工作表(带 SHEETNAMES) - How to write multiple sheets(WITH SHEETNAMES) in excel using openpyxl and python 如何使用 Python 3 和 Pandas 从多个 Excel 工作表中提取相同的行号并将其放在一起? - How can I use Python 3 and pandas to extract and put together same row numbers from multiple excel sheets? 如何使用 Python 将多个 CSV 文件合并为一个具有不同工作表的 Excel 文件 - How do I combine multiple CSV files into one excel files with different sheets using Python 如何将多个 Pandas 数据帧写入 Excel? (当前方法 Corrupts.xlsx) - How to Write Multiple Pandas Dataframes to Excel? (Current Method Corrupts .xlsx) Pandas,(Python) -> 导出到带有多张工作表的 xlsx - Pandas,(Python) -> Export to xlsx with multiple sheets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM