Averages of elements in various lists

Asked

Viewed 43 times

0

I need to calculate the sum of several elements in different lists (from index 0).

lista1 = [154,12,998,147]
lista2 = [897,123,998,59877]
lista3 = [3,789,111,555,699]

That would be the simplistic way:

soma = lista1[0]+lista2[0]+lista3[0]

but I need to extract the values and apply the methods rolling().sum()

lista4 = pd.Series([154,897,3])
lista4.rolling(2).sum()

something like that !!

  • Need only at index 0 or all?

  • only the 'zero'

  • And what exactly is the problem of accessing them directly, as you did in the example?

  • The original list is multidimensional, when I try to access the values I need by index (example[0][0]) and add to an external list, the error message: Object 'Nonetype' Not subscribed.

  • 1

    It’s not very clear what the problem is - it would be nice if you added code demonstrating exactly what problem you’re having with the error message. The way you did it seems okay

1 answer

1

If you have a list of lists:

lista1 = [154,12,998,147]
lista2 = [897,123,998,59877]
lista3 = [3,789,111,555,699]

listas = [lista1, lista2, lista3]

You can create a list of the first elements by doing:

primeiros = [lista[0] for lista in listas]

Thus, primeiros will be the list [154, 897, 3].

As suggested in the comments, one possibility is to define a function that returns the values of a given list index:

def get_on_index(*listas, index=0):
    return [lista[index] for lista in listas]

So if you need all the values in index 2, just do:

valores = get_on_index(lista1, lista2, lista3, index=2)  # [998, 998, 555]
  • Good answer! To get perfect would just replace listas = [lista1, lista2. lista3] for listas = [lista1, lista2, lista3], I think you just put a . where he wanted to put a ,. Improving further, it would perhaps create a function for the loop and instead of passing the 0, you received as argument. D

  • This is the data set I have: data = pd.Dataframe([[['01-09-2018',1,111,100],['01-10-2018',1,111,200],['01-11-2018',1,111,299]], [['01-09-2018',1,222,54],['01-10-2018',1,222,30],['01-11-2018',1,222,90]], [['01-09-2018',1,333,1002],['01-10-2018',1,333,950],['01-11-2018',1,333,100]]]). Within each precise line of the last value of each list/cell to apply the rolling() formula. As in the example, I need to do the sum of 100 + 200 +299 (from the first line);

Browser other questions tagged

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