Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

module 'scipy' has no attribute 'norm'

Tags:

python

scipy

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

like image 797
pythonist jr Avatar asked Apr 08 '26 04:04

pythonist jr


2 Answers

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.

like image 121
Gerardo Zinno Avatar answered Apr 09 '26 17:04

Gerardo Zinno


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.

like image 39
DYZ Avatar answered Apr 09 '26 19:04

DYZ