0

I have a list of matrices as follows:

myarrlist = [array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), array([[10, 20, 30],40, 50, 60],[70, 80, 90]])]

and,

sum(myarrlist)/float(len(myarrlist))

gave me the following result (which is what I require: result of matrix addition is a matrix)

array([[  5.5,  11. ,  16.5],[ 22. ,  27.5,  33. ],[ 38.5,  44. ,  49.5]])

But, when I gave

from numpy import *

for using dot() function for matrix multiplication, sum() function no longer gives a matrix as result but a single value (adding all elements). I am new to python and I am guessing sum() from numpy overrides the call to python built-in sum().

I am trying to add the matrices in the list without loops and find built-in sum() suitable for that. Is it possible to use python sum() and still use other features of numpy?

3
  • 4
    That's exactly what happens. What you can do to avoid namespace collisions is to only import what you need: from numpy import dot for example. Commented Jul 23, 2012 at 23:42
  • 3
    Or another standard is to do import numpy as np, use np.array, np.<function> for all numpy functions and then sum for inbuilt. (Note: np.sum(myarrlist, axis=0) will do as you request - see help(np.sum): numpy sees myarrlist as a 3D matrix so you have to tell it you only want to sum along axis 0) Commented Jul 23, 2012 at 23:44
  • By the way, NumPy arrays support a .dot() method that does what you'd expect :) Commented Oct 29, 2012 at 12:50

2 Answers 2

5

When you do

from SomeModule import *

you are indeed overriding the builtin sum function. This imports everything from numpy's namespace into the default namespace. What you probably want to do instead is:

import numpy as np

You can then access the numpy dot function as np.dot. By doing it this way you can keep namespaces from stomping on each other if they define the functions of the same name.

Another option, if you just want the dot function is to do this:

from numpy import dot

Then the dot function is then the only function from numpy that would be available. These are the two main approaches taken when using other modules. Import * is generally frowned upon because the never know if different modules will stomp on each other or override builtin functions.

Sign up to request clarification or add additional context in comments.

Comments

4

That's exactly what happens. One way you can avoid namespace collisions is to only import what you need: from numpy import dot for example. Another way is to do import numpy or import numpy as np, and refer to dot as np.dot() or numpy.dot()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.