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)
原文地址:https://www.cnblogs.com/oikoumene/p/12916621.html