首页 > 解决方案 > Python模块没有属性而属性存在

问题描述

这里得到帮助,我正在编写自己的包。我有一个文件夹filter,其中包含__init__.py(完全空的)和pca.py. pca.py有一个类pca,该类有一个带有performPCA两个参数的方法。然后,我有这个代码:

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

当我运行它时,我收到一个错误

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

我知道这个问题在这里有答案,但我有答案所要求的一切(唯一的区别是 my__init__.py是空的,我认为这完全没问题)。请告诉我我哪里错了。谢谢!

test.py如下:

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如下:

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

标签: python

解决方案


既然你在里面有另一个类pca.py,你应该先尝试创建一个对象,然后再访问它。

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

推荐阅读