如何使用python将选定的工作表组合到同一工作簿中

问题描述 投票:0回答:1

需要一个建议

我的代码:

import pandas as pd
import openpyxl
df = pd.read_excel('workbook.xlsx', sheet_name='Sheet1')  
df_writer = pd.ExcelWriter('workbook.xlsx', engine='openpyxl')
excel = openpyxl.load_workbook('workbook.xlsx')
df_writer.book = excel


for string in ['A','B','C','D','E','F']:
    df[df['column 1'].str.contains(string)].to_excel(df_writer,sheet_name=string)

writer.save()
writer.close()

现在我在这里分离了包含某些字符串并保存在同一工作簿中不同工作表中的数据。

名为“A”,“B”,“C”,“D”,“E”,“F”的每张纸都需要将名为“A”和“B”的纸张组合在一起,以便在同一工作簿中进行进一步分析使用不同的名称说“合并”表单'A'和'B'具有相同数量的列和标题。

任何建议将不胜感激。

python excel
1个回答
1
投票

使用带有A|B的字符串包含方法在列中查找AB值并包含它们,将其保存到新工作表中:

import pandas as pd
import openpyxl
df = pd.read_excel('workbook.xlsx', sheet_name='Sheet1')  
df_writer = pd.ExcelWriter('workbook.xlsx', engine='openpyxl')
excel = openpyxl.load_workbook('workbook.xlsx')
df_writer.book = excel


for string in ['A','B','C','D','E','F']:
    df[df['column 1'].str.contains(string)].to_excel(df_writer,sheet_name=string)

df[df['column 1'].str.contains('A|B')].to_excel(df_writer,sheet_name='Combined')
#Now your excel contains all 'A','B','C','D','E','F' and 'Combined' sheet.

writer.save()
writer.close()
© www.soinside.com 2019 - 2024. All rights reserved.