Topsis法的python實現


TOPSIS (Technique for Order Preference by Similarity to an Ideal Solution )法是C.L.Hwang和K.Yoon於1981年首次提出,TOPSIS法根據有限個評價對象與理想化目標的接近程度進行排序的方法,是在現有的對象中進行相對優劣的評價。
以往的topsis往往在excel中進行計算,但是如果涉及到多時空比較的話,需要計算多次Topsis,因此編程實現比較實用。
def topsis(year,bigc,filefullname):
    topsis={}
    topsis[year]={}
    f=open(filefullname,'a+')
    for cnty in alhdata['cnty']:
        topsis[year][cnty]={}
    for index,row in alhdata[(alhdata['year']==year)&(alhdata['alh']==bigc)].iterrows():
        topsis[year][row['cnty']][row['type']]=row['weight']
    datalist=[]
    for key in topsis[year]:
        datalist.append(topsis[year][key])
    newdata=pd.DataFrame(datalist)
    data2 = (newdata-newdata.min())/(newdata.max()-newdata.min())
    data2=data2.fillna(0)
    collist=list(data2.columns)
    wlist=[(np.std(data2[col])/np.mean(data2[col])) for col in collist]
    best=[data2[col].max() for col in collist]
    worst=[data2[col].min() for col in collist]
    datagood=pd.DataFrame()
    databad=pd.DataFrame()
    for col in collist:
        colindex=collist.index(col)
        datagood[col]=wlist[colindex]*(best[colindex]-data2[col])*(best[colindex]-data2[col])
        databad[col]=wlist[colindex]*(-worst[colindex]+data2[col])*(-worst[colindex]+data2[col])
    for key in topsis[year]:
        index=list(topsis[year].keys()).index(key)
        djia=datagood.iloc[index,:].sum()
        djian=databad.iloc[index,:].sum()
        c=djian/(djia+djian)
        print(year,key,bigc,c,file=f)
    f.close()
    print(year,bigc)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM