如何使用python在同一工作簿中合并选定的工作表

2024-04-26 19:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

需要建议吗

我的代码:

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”的列数和标题数相同。你知道吗

如有任何建议,将不胜感激。你知道吗


Tags: 代码nameimportpandasdfstringasxlsx
1条回答
网友
1楼 · 发布于 2024-04-26 19:03:16

使用带有A|B的string contain方法查找列中的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()

相关问题 更多 >