I need to add some specific lines in a data frame

Asked

Viewed 321 times

0

I need to add the value of the lines in which appears "Resposnsável C', in a practical way I need to add lines 3, 4 and 9 from column 2, the result should be 112. So far I’ve been able to print the lines I want using iloc, but I can’t add them. Follow the code. ps: I need to add what is in red.

import pandas as pd
def trans_excel_py(arquivocsv):
    df = pd.read_csv(arquivocsv, sep=';', header = None)
    return df
def soma_colunas(arquivocsv):
    df = pd.read_csv(arquivocsv, sep=';')
    matriz = pd.DataFrame(df.values)
    somas = []
    for i in range(len(matriz)):
        Total = matriz[i].sum()
        somas.append(Total)
    return somas
teste = trans_excel_py('cronograma.csv')
print(teste)
teste_sum = soma_colunas("cronograma.csv")
df = pd.DataFrame([teste_sum[2:10]],columns=['S1', 'S2', 'S3','S4','S5','S6','S7','S8'])
print("\n",df)

print(sum(teste_sum[2:10]))

df1 = teste.iloc[[3,4,9]]
print("\n",df1)

inserir a descrição da imagem aqui

1 answer

0

After selecting the lines, as you did:

df1 = teste.iloc[[3,4,9]]

df2 = df1.sum(axis=1) # soma cada linha individualmente no eixo horizontal

df2.sum() # soma os resultados de cada linha

It’s also possible to do everything in one line:

teste.iloc[[3,4,9]].sum(axis=1).sum()

More information is in the documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sum.html

To also select the columns that will be used (from 2 to 9):

teste[[2,3,4,5,6,7,8,9]].iloc[[3,4,9]].sum(axis=1).sum()

You can also replace the NaN for some value using fillna(valor):

teste[[2,3,4,5,6,7,8,9]].iloc[[3,4,9]].fillna(0).sum(axis=1).sum()
  • Unfortunately it did not work, it did not return any result... It is not that it is wrong it just does not return the sum of what is in red. I tried with only one line (the 3 that should return me the answer of the sum as 24) but in the end it resulted me as 0.0. To be more specific I don’t want the sum of the whole row, just the sum of the row going from column 2 to column 9.

Browser other questions tagged

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