0

Taking help from here, I was writing my own package. I have a folder filter which contains __init__.py (completely empty) and pca.py. pca.py has a class pca and that class has a method performPCA which takes two arguments. Then, I have this code:

from filter import pca
....
pca.performPCA(x,2)

When I run this, I'm getting an error

AttributeError: module 'filter.pca' has no attribute 'performPCA'

I know this question has an answer here, but I have everything that answer asks (the only difference is that my __init__.py is empty, which I think is totally fine). Please tell me where am I wrong. Thanks!

test.py goes as:

from filter import pca
print(pca)
import pandas as pd

x=pd.read_csv('Assignment-DS_gene_data.csv')
meta=pd.read_csv('Assignment-DS_Meta_data_sheet_.csv')
x.rename(columns={'Unnamed: 0':'col1'}, inplace=True )
del x['symbol']
del x['col1']
p=pca.pca2
#print(p)
xNew=p.performPCA(x,2)

pca.py goes as:

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D

class pca2:
    #Choose this method if only projected data is required
    def perfromPCA(self,data,nComp):
        pcaModel = PCA(n_components=nComp)
        principalComponents = pcaModel.fit_transform(data)
        colNames = []
        for i in range(1,nComp+1):
            colNames.append('PC '+str(i))
        principalDf = pd.DataFrame(data = principalComponents
             , columns = colNames)
        return principalDf

    #Choose this method if plot and projected data both are required
    #For this, nComp can either be 2 or 3
    def performPCAPlot(self,data,nComp,metaData,column):
        principalDf = performPCA(data,nComp)
        if nComp == 2:
            plt.scatter(principalDf,data=metaData['column'])
            #plt.xlabel('PC1')
            #plt.ylabel('PC2')
            plt.show()
        else:
            fig = plt.figure()
            #to do
        return principalDf
Ankit Kumar
  • 1,145
  • 9
  • 30
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/194109/discussion-on-question-by-ankit-kumar-python-module-has-no-attribute-while-the-a). – Samuel Liew May 29 '19 at 11:26

2 Answers2

0

Since you have another class inside pca.py, you should try creating an object first and then accessing it.

from filter import pca
....
p = pca()
p.performPCA(x,2)
MePsyDuck
  • 364
  • 2
  • 15
-1

Create an object first and then call the function on that object.

myPCA = pca()
myPCA.performPCA(x,2)

Edit

You are creating a python package by adding the _ init _.py file in the filter directory further reading subsection 6.4

You can import and use it like this (working for me with python 3.7.0)

from filter.pca import pca

myPCA = pca()
myPCA.performPCA(2,2)

or after renaming the class to pca2:

from filter.pca import pca2

myPCA = pca2()
myPCA.performPCA(2,2)

lidrariel
  • 79
  • 6