TOPSIS法

TOPSIS法_第1张图片

import numpy as np
import pandas as pd
def topsis(file_path, weights, criteria):
    data = pd.read_excel(file_path)
    matrix = data.values
    n, m = matrix.shape
    for j in range(m):
        if criteria[j] == 'max':
            matrix[:, j] = matrix[:, j] / np.sqrt(np.sum(matrix[:, j] ** 2))
        elif criteria[j] == 'min':
            min_value = np.min(matrix[:, j])
            matrix[:, j] = np.where(matrix[:, j] == 0, 1e-10, matrix[:, j])  # Replace zeros with a small number
            matrix[:, j] = min_value / matrix[:, j]
            matrix[:, j] = matrix[:, j] / np.sqrt(np.sum(matrix[:, j] ** 2))
    weighted_matrix = matrix * weights
    ideal_solution = np.max(weighted_matrix, axis=0)
    negative_ideal_solution = np.min(weighted_matrix, axis=0)
    distance_to_ideal = np.sqrt(np.sum((weighted_matrix - ideal_solution) ** 2, axis=1))
    distance_to_negative_ideal = np.sqrt(np.sum((weighted_matrix - negative_ideal_solution) ** 2, axis=1))
    score = distance_to_negative_ideal / (distance_to_ideal + distance_to_negative_ideal)
    return score
file_path = r"C:\Users\云倩怡\Desktop\302(十个指标)【正向化的】.xlsx"  # 替换为你的Excel文件路径
weights = [0.1282,0.1537,0.1172,0.0255,0.0349,0.1102,0.2076,0.2205,0.0001,0.0019,0.0005]
criteria = ['max','max','max', 'max','max', 'max','max','max','max','max','max']
scores = topsis(file_path, weights, criteria)
# 将结果保存到Excel文件中
output_file_path = r"C:\Users\云倩怡\Desktop\302(十个指标).xlsx"  # 替换为你的输出Excel文件路径
output_df = pd.DataFrame({
    '企业': [f'企业 {i + 1}' for i in range(len(scores))],
    '评分': scores
})
# 保存到Excel
output_df.to_excel(output_file_path, index=False)

你可能感兴趣的:(数据分析)