2

I am new to python and I am trying to understand why I am not being able to graph a plot. First I imported all of the libraries I have been using in the program:

import pandas as pd
import statsmodels.formula.api as sm
import numpy as np
import seaborn as sns
import scipy as stats
import matplotlib.pyplot as plt

And when I run the following code:

sns.distplot(financials.residual,kde=False,fit=stats.norm)

I get the following error:

AttributeError: module 'scipy' has no attribute 'norm'

I believe it might be because I am not importing the correct module from spicy but I can't find the way to get it right.

Thanks for your help

pythonist jr
  • 33
  • 1
  • 6

3 Answers3

4

norm is in scipy.stats, not in scipy. Importing "scipy as stats" simply imports scipy and renames it to stats, it doesn't import the stats submodule inside scipy.

do

from scipy.stats import norm

like on the official website example

or

from scipy import stats
stats.norm(...)

Note: when "importing something as somethingelse", be careful to not shadow other names and if possible follow conventions (like import numpy as np).

For scipy, as explained in this answer, the convention is to never "import scipy as ..." since all the interesting functions in scipy are actually located in the submodules, which are not automatically imported.

Gerardo Zinno
  • 1,518
  • 1
  • 13
  • 35
3

Do not import scipy as stats. There is a library module called stats. By renaming scipy, you shadow the original stats module and prevent Python from accessing it. Then stats.norm essentially becomes scipy.norm, which is not what you want.

DYZ
  • 55,249
  • 10
  • 64
  • 93
1

First of all, let's see how to make proper use of import:

1)Importing a Library: The first method is to import the library directly and access the modules under it with a '.'. This is illustrated here:

import pandas
import numpy
pandas.read_csv('helloworld.csv')

pandas is a library and read_csv is a module inside it.

2)Importing the module directly The second method is to import the module directly as follows:

from pandas import read_csv
read_csv('helloworld.csv')

Use this method when you know that you'll only be using read_csv module of pandas and not any other module under it.

3)Importing all the modules under a library

from pandas import *

This will import all the modules under the pandas library and you can use them directly.

Now coming to your question:

The norm function is present inside the stats module of scipy. When you use as, you're giving an alias for the library/module inside your code. So instead try this method

from scipy.stats import norm
norm(...)

or

from scipy import stats
stats.norm(..)

Hope this helps!

Raghul Raj
  • 1,428
  • 9
  • 24