5

Given three lists:

A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]

How do I calculate the mean of the following (the columns)?

  • Mean of [1, 4, 7]
  • Mean of [2, 5, 8]
  • Mean of [3, 6, 9]

Not the following (the rows),

  • Mean of [1, 2, 3]
  • Mean of [4, 5, 6]
  • Mean of [7, 8, 9]

import numpy as np
A = np.array([1,2,3])
B = np.array([4,5,6])
C = np.array([7,8,9])

What should I do?

3
  • 3
    It's clearly written in the docs : docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html Commented Nov 10, 2013 at 5:28
  • this question is not just about calculating mean but before that lists have to be arranged, but how?@ Raiyan Commented Nov 10, 2013 at 5:38
  • This question should not be closed as off-topic, but a duplicate probably exists (given it is so basic (or others have posted the same home work-like question)). Commented Mar 3, 2014 at 20:58

2 Answers 2

4

Using numpy.ndarray.transpose:

>>> np.array([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).transpose().mean(axis=1)
array([ 4.,  5.,  6.])

or using numpy.transpose:

>>> np.transpose([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).mean(axis=1)
array([ 4.,  5.,  6.])

UPDATE

As Dave Hirschfeld commented, mean over axis=0 is alot better:

>>> np.array([
...     [1,2,3],
...     [4,5,6],
...     [7,8,9]
... ]).mean(axis=0)
array([ 4.,  5.,  6.])
Sign up to request clarification or add additional context in comments.

2 Comments

Even though a transpose in numpy simply returns a different "view" on the underlying data and doesn't actually copy or move any data it still seems a bit redundant - just take the mean over axis=0
@DaveHirschfeld, Thank you for comment. I updated the answer according to your comment. Sorry for responding too late.
1
import numpy as np
A = np.array([1,2,3])
B = np.array([4,5,6])
C = np.array([7,8,9])

Z = zip(A,B,C)

for z in Z :
    print np.mean(np.asarray(z))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.