package import is not importing its dependencies - python

I just wrote a small package containing a class to use on jupyter labs at work, however when I try to import and use the class which is dependent on numpy and matplotlib, it says that np is not defined.
Even though it is imported into the file I am importing the class into, and I imported it into the class file itself that I am importing, and the __init__.py file for the package. I just need the class to load some data into a np.array([]) via np.genfromtxt().
I have made one package before and didn't have any issues but I'm new so am obviously missing something.
Here's how I get the error:
pip install git+https://github.com/Elliot-Wadge/pl_class#egg=pl_class
import numpy as np
import matplotlib.pyplot as plt
import glob
from pl_data import pl_data as pl
PL_data = pl.PL_data
flist = glob.glob("data/*")
dictionary = PL_data(flist, skip_header = 4, unpack = True, delimiter = '\t')
error message
class file

Related

Jupyter imported module not using library

I made an external module model.py and I want to import it within my Jupyter notebook.
# model.py
import numpy as np
import pandas as pd
from scipy.stats import chi2
from sklearn.covariance import EllipticEnvelope
from sklearn.base import BaseEstimator
from scipy.stats import combine_pvalues
# ...
def predict(self, xtest):
return np.where(self.predict_proba(xtest, False) < self.critical_value, 1., -1.)
When I try to call the predict method of my model class I get the error:
NameError: name 'np' is not defined.
I have the numpy library installed and I am strugggling to understand why it is not able to use it.
Any ideas?

Python not recognizing sub module in Jupyter

I have a problem using python module in Jupyter. It was working fine until yesterday. The only new thing is that I updated Seaborn to th elatest version. I do not have the pb when I use Spyder directly.
For exemple, I have a file that would be like :
import numpy as np
import pandas as pd
import scipy
def test_skewn(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
I work perfectly from Spyder but from Jupyter it return :
AttributeError: module 'scipy' has no attribute 'stats'
If I correct it like this :
import numpy as np
import pandas as pd
#import scipy
from scipy.stats import skew, kurtosis
def test_skewness(TimeSeries):
tempTimeSeries = TimeSeries.copy()
temp_Rolling_Perf = (tempTimeSeries / tempTimeSeries.shift(1) -1 ).dropna()
#current_skew = scipy.stats.skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
current_skew = skew(temp_Rolling_Perf.iloc[i:i+Maturity-1])
return(current_skew )
It works in Jupyter.
It was working with both version before and I am not confortable at all with this pb and I would like to understand where it can come from.

Cannot import class from module (circular reference issue?)

I've seen countless issues here on stack about this but still can't figure out why I cant get mine to work. I have a 2 .ipynb files and I'm looking to import a class from one file to the other as follows:
CV_Screening_Interface:
from joblib import dump, load
import sys
import pandas as pd
import os
import import_ipynb
import docx
import readDocx ***(This is another ipynb file)***
from docx import Document
import string
model = load('model.joblib')
class CV:
def __init__(self,university,major,masters,company,certification,GPA):
self.university = university
self.major = major
self.masters = masters
self.company = company
self.certification = certification
self.GPA = GPA
#And a bunch of other functions
Now in FirstProgram
from tkinter import *
from tkinter import filedialog
from docx import Document
import io
import import_ipynb
import CV_Screening_Interface
#Till here works fine
When I try to import class CV I get an import error
from CV_Screening_Interface import CV
OR
test = CV_Screening_Interface.CV()
ImportError: cannot import name 'CV' from 'CV_Screening_Interface' (CV_Screening_Interface.ipynb)
I checked PYTHONPATH, I have an empty init.py in the directory already. What's weird is that importing the module works, but importing the class in the module doesn't.
Note in CV_Screening_Interface CV class works perfectly fine so I don't think there is any issue with it specifically. Probably need a if name="main" inside it?
Ok so this solved my problems:
I created a new ipynb called ClassFile.ipynb and it only contains the Class CV without importing any packages
Then i converted ClassFile.ipynb to ClassFile.py and imported it to FirstProgram and it worked.

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Python: Import networkx as nx: Global name not defined

I wrote a module (processing_0) in which I import all packages and modules required for my project.
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import collections
import la
import csv
import fishery
import re
from collections import OrderedDict
import processing_1
import processing_2
import processing_3
from processing_1 import readingraph, readinpathgraph, preparefisher, inEEG
from processing_2 import pathwayprofile
from processing_3 import checkkin
from fishery import fisher
The modules that I wrote (processing_1/2/3) all require access to networkx (nx).
As part of the master module, I have a the startup function:
def startup():
EEG = readingraph("/.../file1")
EET = readingraph("/.../file2")
EEL = readingraph("/.../file3")
return EEG, EET, EEL
However, after importing processing_0 and trying to run startup() that uses readingraph from processing_1, I keep getting the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "processing_0.py", line 31, in startup
EEG = readingraph("/.../file1")
File "processing_1.py", line 4, in process
graph = nx.read_adjlist(filename)
NameError: global name 'nx' is not defined
Is there any way to globally import networkx as nx and make it accessible to all imported modules?
if you are using linux ubuntu, do these followings in order.
sudo apt-get update
sudo apt-get install python-networkx
go to pycharm env and > file>setting> interpreter and structure to
configure your python env and add packages, there is all packages
that are in env, then click on + to add newpackage
type networkx in search text box, and then select it from package
list and click on install
after finish it , click ok and close windows
In every file that you use networkx you need to import it. So just repeat the line
import networkx as nx
inside the file processing_1.py

Categories