2

I am new to Python programming, so please bear with my nascent question.

If we want to use certain function inside numpy, say func, do we need to just import numpy once and then call the function as following:

import numpy
np.func

Or, do we further need to import specific sub modules of numpy before calling any function? Thanks.

3 Answers 3

3

Almost, if you want to use numpy as np you have to import it like this:

import numpy as np

Other than that you can use the functions like that.

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

1 Comment

If I write import numpy, then I have to write numpy.func?
3

As with every other fricking module in existence, you use the name you import it as.

import numpy
numpy.func

...

import numpy as np
np.func

3 Comments

To be fair, there are plenty of modules where a particular sub-module isn't included in the __init__ for the main module. I'm guessing the OP's questions stems from scipy. scipy's __init__ basically just imports numpy. All of scipy's functionality is in submodules that you have to explicitly import.
@Joe: You get what you import. That hasn't changed.
No, it hasn't, but if the OP is using numpy, they're probably using scipy as well. It's common to be confused as to why there's so much code similar to import scipy.ndimage and why you can't just do import scipy and then access scipy.ndimage. Or maybe I'm just reading too much into the question.
2

If you want to use linalg you have to do:

numpy.linalg

For example, if you want to calculate determinant of x, you would do

import numpy

x = numpy.array([[1,2],[5,7]])
det_x = numpy.linalg.det(x)

#or

import numpy as np

x = np.array([[1,2],[5,7]])
det_x = np.linalg.det(x)

2 Comments

Thanks. Do you know any good source to learn about those submodules inside numpy and scipy?
I find manuals of type "Numpy for Matlab users" to be quite good, especially to get started. Even though I am hardly a matlab user, they have helped me.

Your Answer

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