Sum of column totals

Asked

Viewed 4,781 times

1

I own this dataset: inserir a descrição da imagem aqui I would like to create command to sum up the values of each year, and put in a list.

  lista=[]
  for i in range(2008, 2041):
   area[i].sum()
    lista.append(i)

But it didn’t work out the way I did, I’d like some help.

2 answers

1


I assumed you’re using pandas.

Anyway, starting from this:

import pandas as pd

d = {'Distritos': ['Local1', 'Local2'], '2017': [30, 40], '2018': [50, 60]}
df = pd.DataFrame(data=d)
>>> print df
   2017  2018 Distritos
0    30    50    Local1
1    40    60    Local2

I take the years like this:

anos = list(df.columns.values)
anos.remove('Distritos')
>>> print anos
['2017', '2018']

Add all from the same year:

lista = []
for ano in anos:
    lista.append(df[ano].sum())
>>> print lista
[70, 110]

Sum all values of each region:

lista = []
for i in range(len(df)): #para cada região
    soma = 0
    for ano in anos: #seleciono os anos
        soma += df.iloc[i][ano]
    lista.append(soma)
>>> print lista
[80, 100]
  • It didn’t work out that way

  • But I did so: lista=[]
 for i in range(2008, 2021):
 tes=area[i].sum()
 lista.append(tes) E worked, but the problem is that in the dataset after 2020 the interval is 5 and 5 and gives error.

  • Check now with the edition I made...

  • Worked perfectly

0

first try using for as long as a given exists.

lista = []
for i in arq:
    arq.split('?') #o '?' é o que separa cada índice no seu arquivo ou variável que contém a informação que quer

this way you have rows and columns now and the next step is just see which range of index you want to add

i = 2
sum = 0
for i in range(n): #n tem que ser o numero de colunas que quer percorrer
 sum = sum + arq[i] 
lista.append(sum)

the complete code gets:

lista = []
for i in arq:
    arq.split('?')
    sum = 0
    for j in range(2,n): #n tem que ser o numero de colunas que quer percorrer
        sum = sum + arq[j] 
    lista.append(sum)

Browser other questions tagged

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