Python Forum

Full Version: Filter value from DataFrame apply a function and save to xlsx
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
After read my df I need filter to get specific values then use a function, add a column in this new df then save to excel file.
import pandas as pd
colunas = ['Tipo_Lanc','UF','Fis/Jur','CNPJ','RAZAO_SOCIAL','NF','Data_Emissão','DT_Fiscal',
           'Data_Lançamento','PRODUTO','DESCRICAO','NUM_ITEM','Unid','LISTA','NCM','Monit/Liber',
           'EAN','MVA_Original','MVA','CFOP','CST','QUANTIDADE','PF_UNIT','PF_TOTAL','VLR_LIQ_UNIT',
           'VLR_LIQ_ITEM','VL_UNIT_NF','TOTAL_NF','VL_UNIT_LIQ_NF','TOTAL_LIQ_NF','DESC._TOT','DESCONTO',
           'REPASSE','VC','BC','ICMS','BC_Não_Escriturado','ICMS_Não_Escriturado','ALIQ_ICMS','APROPRIA',
           'BC_ICMS_ST','ICMS_ST','ALIQ_INTERNA','DEB_ICMS','IPI','CAT_ANVISA','TIPO_PRODUTO','TIPO_DESCONTO',
           '%_DESCONTO','PMC','PMC_FCIA_POP','%_REDUTOR_ANVISA','CROSS','INDICADOR_ICMSS','BC_ICMS_ST_REC',
           'ICMS_ST_REC','MCANCER','CBASICA']
df = pd.read_excel('fat.xlsx', sheet_name='Geral')
df.columns=colunas

# After read df, I need get this two peace of DataFrame
cfop_5403 = df[df['CFOP'] == 5403]
cfop_5102 = df[(df['CFOP'] == 5102)]

# But I need use this function before save to excel file
def substi_trib(x):

    if x['Monit/Liber'] == 'M':
        if (x['CAT_ANVISA'] == "Generico") | (x['CAT_ANVISA'] == "Similar"):
            return x['PMC']*x['QUANTIDADE']*0,50*0,17-x['ICMS']
        elif (x['CAT_ANVISA'] == "Outros") | (x['CAT_ANVISA'] == ""):
            return x['PMC']*x['QUANTIDADE']*0,90*0,17-x['ICMS']
        elif (x['CAT_ANVISA'] == "Referencia"):
             return x['PMC']*x['QUANTIDADE']*0,88*0,17-x['ICMS']
        else:
            return 0

    if x['Monit/Liber'] == 'L':
        return 1 + x['MVA'] * x['TOTAL_LIQ_NF'] * 0,17 - x['ICMS']
    
# How can I add acolumn and write a function result in this column, after save as sheet into excel file?
cfop_5403['col_test'] = cfop_5403.apply(substi_trib, axis=1)


# I would like write result in excel. 
with pd.ExcelWriter('teste.xlsx', engine='xlsxwriter') as ex:
    cfop_5403.to_excel(ex, sheet_name='CFOP_5403', index=False)
    cfop_5102.to_excel(ex, sheet_name='CFOP_5102', index=False)
Thank you
I solved this.
I put my filter after function
Thanks