Create a new sheet with specif data from DF but if column doesn't match just pass

Viewed 20

As i briefly described on the Title i have the follow code (inside a function) which should skip the function (do nothing) if the passed variable grupomaquina_ref IS NOT in the 'Grupo Máquina' column. I'm facing this *KeyError: "None of [Index([all list indexes here]dtype='object')] are in the [index]"

import numpy as np
from openpyxl import load_workbook

df = pd.read_excel('folha1.xlsx')

#create a sheet 'grupomaquina_ref' but if in 'grupo máquina' column indexes of df doesn't exist, just pass.

def createsheets(grupomaquina_ref, sheetname):
    grupomaquina_ref = pd.DataFrame(df.loc[df['Grupo Máquina']==grupomaquina_ref])
    if grupomaquina_ref not in pd.DataFrame(df.loc[df['Grupo Máquina']]):
        pass
    else:
        with pd.ExcelWriter("folha1.xlsx", mode="a", engine="openpyxl") as writer:
            grupomaquina_ref.to_excel(writer, sheet_name=sheetname)

#'MACARRAO' is not in the column 'Grupo Máquina' so it was expected to 'do nothing'.

createsheets('MACARRAO', 'batata')
1 Answers

Use grupomaquina_ref.empty to check if your dataframe is empty or not:

def createsheets(grupomaquina_ref, sheetname):
    grupomaquina_ref = df[df['Grupo Máquina'] == grupomaquina_ref]
    if not grupomaquina_ref.empty:
        with pd.ExcelWriter('folha1.xlsx', mode='a', engine='openpyxl') as writer:
            grupomaquina_ref.to_excel(writer, sheet_name=sheetname)

createsheets('MACARRAO', 'batata')
Related