Find avg value from list having single element

Viewed 44

The list contain single element with the array values. list is [array([[ 4, 5, 6], [10, 11, 12]])]. I need average of each value of tensors. For example here there are 2 tensor with 3 values so i need 3 values([7 8 9] in this case) with average of it. Find below code for reference.

import numpy
a=np.arange(1,13).reshape(2,2,3)
pt=[np.array([0,1]),np.array([1,1])]
list=[]
list.append(a[pt[0],pt[1]])
2 Answers

Do this:

import numpy as np
np.mean(list, axis=1)[0]  # the list here refers to list you've created

This will return:

array([7., 8., 9.])

Quick solution:

import numpy as np
np.mean(list[0], axis=0)

Bugs and cautions on your example though:

  1. NEVER name your variable is list, dict or other built-in functions/types/keywords. Ideally use phrases relevant to the content, and meaningless varname is still better than overriding default functions.
  2. import numpy as np rather than import numpy. Or you can simply import numpy and then write the lines afterwards with numpy.array instead of np.array.
Related