数据源是一个excel文件,写一个topsis法代码
时间: 2024-05-12 16:15:25 浏览: 145
好的,首先需要导入 pandas 和 numpy 库来读取和处理数据。
```python
import pandas as pd
import numpy as np
```
然后读取数据文件并将其转换为 pandas 数据框。
```python
data = pd.read_excel('data.xlsx')
```
接下来,我们需要对数据进行标准化处理。
```python
normalized_data = (data-data.min())/(data.max()-data.min())
```
然后,我们可以计算正向指标和负向指标。
```python
positive = [1, 1, 1, 1, 1, 1] # 正向指标
negative = [0, 0, 0, 0, 0, 0] # 负向指标
```
接下来,我们可以计算评价矩阵。
```python
weighted_data = normalized_data * positive + (1-normalized_data) * negative
```
然后,我们可以计算加权后的矩阵。
```python
weights = [0.2, 0.15, 0.15, 0.1, 0.25, 0.15] # 权重向量
v = np.sqrt(np.sum(np.power(weighted_data, 2), axis=1)) # 各方案的综合评价值
weighted_matrix = weighted_data.copy()
for i in range(len(weights)):
weighted_matrix.iloc[:,i] = weighted_matrix.iloc[:,i] * weights[i]
s_plus = np.max(weighted_matrix, axis=0)
s_minus = np.min(weighted_matrix, axis=0)
d_plus = np.sqrt(np.sum(np.power(weighted_matrix-s_plus, 2), axis=1))
d_minus = np.sqrt(np.sum(np.power(weighted_matrix-s_minus, 2), axis=1))
c = d_minus / (d_plus + d_minus)
```
最后,我们可以将方案按照其综合评价值排序。
```python
result = pd.DataFrame({'方案': data['方案'], '综合评价值': v, '排序': c}).sort_values(by='综合评价值', ascending=False)
print(result)
```
完整代码如下:
```python
import pandas as pd
import numpy as np
data = pd.read_excel('data.xlsx')
normalized_data = (data-data.min())/(data.max()-data.min())
positive = [1, 1, 1, 1, 1, 1]
negative = [0, 0, 0, 0, 0, 0]
weighted_data = normalized_data * positive + (1-normalized_data) * negative
weights = [0.2, 0.15, 0.15, 0.1, 0.25, 0.15]
v = np.sqrt(np.sum(np.power(weighted_data, 2), axis=1))
weighted_matrix = weighted_data.copy()
for i in range(len(weights)):
weighted_matrix.iloc[:,i] = weighted_matrix.iloc[:,i] * weights[i]
s_plus = np.max(weighted_matrix, axis=0)
s_minus = np.min(weighted_matrix, axis=0)
d_plus = np.sqrt(np.sum(np.power(weighted_matrix-s_plus, 2), axis=1))
d_minus = np.sqrt(np.sum(np.power(weighted_matrix-s_minus, 2), axis=1))
c = d_minus / (d_plus + d_minus)
result = pd.DataFrame({'方案': data['方案'], '综合评价值': v, '排序': c}).sort_values(by='综合评价值', ascending=False)
print(result)
```
阅读全文