Return in a Dataframe - Python

Asked

Viewed 129 times

2

Good afternoon. I have a question about Python. I have an if where he has the conditional and Else, the Else he processes more than one file and I need to save all the information he reads inside a Dataframe, there is a way to do this?

The code I’m using:

for idx, arquivo in enumerate(fileLista):
    if arquivo == 'nome_do_arquivo_para_tratamento':
        df1 = pd.read_excel(arquivo, sheet_name = sheetName[idx], skiprows=1)
        df1.columns = df1.columns.str.strip()
        tratativaUm = df1[[informacoes das colunas que vão ser utilizadas]]

     else:
        df2 = pd.read_excel(arquivo, sheet_name = sheetName[idx], skiprows=1)
        df2.columns  = df2.columns.str.strip()
        TratativaDois = df2[[informacoes das colunas que vão ser utilizadas]]

####atribuir resultado de cada arquivo recebido no else

frames = [tratativaUm, tratativaDois] 
titEmpresa = pd.concat(frames)

Can someone help me ? Thank you

1 answer

2


Hello!

Assuming that all read files have the same structure, each Dataframe created on else will have the same columns. So, just add the Dataframes read in the result Dataframe in each iteration.

# Inicializar DataFrame resultado
tratativaDois = pd.DataFrame()    

for idx, arquivo in enumerate(fileLista):
    if arquivo == 'nome_do_arquivo_para_tratamento':
        df1 = pd.read_excel(arquivo, sheet_name = sheetName[idx], skiprows=1)
        df1.columns = df1.columns.str.strip()
        tratativaUm = df1[[informacoes das colunas que vão ser utilizadas]]

    else:
       df2 = pd.read_excel(arquivo, sheet_name = sheetName[idx], skiprows=1)
       df2.columns  = df2.columns.str.strip()

       # Acrescentar novo DataFrame lido
       tratativaDois = tratativaDois.append(df2[[informacoes das colunas que vão ser utilizadas]])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.