Tenho uma planilha grande do Excel. Só me interessam certas colunas. Além disso, só me interessam linhas em que colunas específicas atendem a determinados critérios.
As seguintes obras:
import pandas as pd
import warnings
# this suppresses the openpyxl warning that we're seeing
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")
# These are the columns we're interested in
COLUMNS = [
"A",
"B",
"C"
]
# the source file
XL = "source.xlsx"
# sheet name in the source file
SHEET = "Sheet1"
# the output file
OUTPUT = "target.xlsx"
# the sheet name to be used in the output file
OUTSHEET = "Sheet1"
# This loads the entire spreadsheet into a pandas dataframe
df = pd.read_excel(XL, sheet_name=SHEET, usecols=COLUMNS).dropna()
# this replaces the original dataframe with rows where A contains "FOO"
df = df[df["A"].str.contains(r"\bFOO\b", regex=True)]
# now isolate those rows where the B contains "BAR"
df = df[df["B"].str.contains(r"\bBAR\b", regex=True)]
# output to the new spreadsheet
df.to_excel(OUTPUT, sheet_name=OUTSHEET, index=False)
Isso funciona. No entanto, não consigo deixar de pensar que pode haver uma maneira melhor de gerenciar os critérios de seleção, especialmente se/quando eles se tornarem mais complexos.
Ou será que o "passo a passo" é bom?