import pandas as pd #导入pandas工具包
import numpy as np #导入numpy工具包
data = pd.read_excel(r"C:\数据集\data.xlsx",sheet_name="汇总数据")
data[:5]
# 设置城市名为索引
#data.set_index(['Unnamed: 0'], inplace=True)
# 获取列名称
n = list(data.columns)
# 高优指标
for i in n:
data[i] = data[i]
# 低优指标
for i in n:
data[i] = 1/data[i]
# 中性指标
for i in n:
Max = np.max(data[i])
data[i] = Max/(Max + np.abs(data[i] - Max))
# 进行归一化
for i in n:
x = np.power(np.sum(np.power(data[i],2)),0.5)
data[i] = data[i]/x
data[:5]
A1 = []
# 获取最优列值
for i in n:
Max = np.max(data[i])
A1.append(Max)
# 转换形式
A1 = np.array(A1)
# 获取最劣列值
A2 = []
for i in n:
Min = np.min(data[i])
A2.append(Min)
# 转换形式
A2 = np.array(A2)
#计算最优方案
D1 = []
for i in range(1,len(data)+1):
d1 = np.power(np.sum(np.power(A1 - data[i-1:i],2).values),0.5)
D1.append(d1)
# 转换形式
D1 = np.array(D1)
# 计算最劣方案
D2 = []
for i in range(1,len(data)+1):
d2 = np.power(np.sum(np.power(A2 - data[i-1:i],2).values),0.5)
D2.append(d2)
# 转换形式
D2 = np.array(D2)
C = D2/(D1 + D2)
# 新建数据框
data1 = pd.DataFrame(C, index = list(data.index))
data2 = pd.DataFrame(D1, index = list(data.index))
data3 = pd.DataFrame(D2, index = list(data.index))
# 按C值进行排序
data1['rank'] = data1.rank(ascending = False)
data2['rank1'] = data2.rank(ascending = False)
data3['rank2'] = data3.rank(ascending = False)
# 对 data1 重新设置列名
data1.columns = ['得分', '排名']
data1['最优方案距离'] = data2[0]
data1['排名1'] = data2['rank1']
data1['最劣方案距离'] = data3[0]
data1['排名2'] = data3['rank2']
data1
# 保存为excel格式
data1.to_excel("C:\数据集\综合得分.xlsx")
data1[:7]