m0_65018173 2022-02-11 17:08 采纳率: 100%

# python进行层次聚类时数据读取出现问题

###### 问题相关代码，请勿粘贴截图
``````#描述: 基于组平均的AGNES算法，支持多维数组，距离用欧式距离
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import dendrogram,linkage
from scipy.spatial.distance import squareform
import matplotlib.pyplot as plt
import math
import pylab as pl
#从excel中读取数据并转换为矩阵
data=np.array(datA,dtype=np.int64)
#数据处理 dataset是样本的列表
a = np.array_split(datA,78,axis=0)
dataset = [(a[i], a[i+1]) for i in range(1, len(a)-1, 3)]
#计算欧几里得距离,a,b分别为两个元组
def dist(a, b):
t = 0
n=44
for i in range(n):
t = t + math.pow(a[i]-b[i], 2)
return math.sqrt(t)
#dist_min
def dist_min(Ci, Cj):
return min(dist(i, j) for i in Ci for j in Cj)
#dist_max
def dist_max(Ci, Cj):
return max(dist(i, j) for i in Ci for j in Cj)
#dist_avg
def dist_avg(Ci, Cj):
return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))
#找到距离最小的下标
def find_Min(M):
min = 1000
x = 0; y = 0
for i in range(len(M)):
for j in range(len(M[i])):
if i != j and M[i][j] < min:
min = M[i][j];x = i; y = j
return (x, y, min)
#算法模型：
def AGNES(dataset, dist, k):
#初始化C和M
C = [];M = []
for i in dataset:
Ci = []
Ci.append(i)
C.append(Ci)
for i in C:
Mi = []
for j in C:
Mi.append(dist(i, j))
M.append(Mi)
q = len(dataset)
#合并更新
while q > k:
x, y, min = find_Min(M)
C[x].extend(C[y])
C.remove(C[y])
M = []
for i in C:
Mi = []
for j in C:
Mi.append(dist(i, j))
M.append(Mi)
q -= 1
return C
#画图
def draw(C):
colValue = ['r', 'y', 'g', 'b', 'c', 'k', 'm']
for i in range(len(C)):
coo_X = []    #x坐标列表
coo_Y = []    #y坐标列表
for j in range(len(C[i])):
coo_X.append(C[i][j][0])
coo_Y.append(C[i][j][1])
pl.scatter(coo_X, coo_Y, marker='x', color=colValue[i%len(colValue)], label=i)

pl.legend(loc='upper right')
pl.show()
C = AGNES(dataset, dist_avg, 3)
draw(C)

``````
###### 运行结果及报错内容
``````Traceback (most recent call last):
File "C:/各种东西练习/1/4.py", line 92, in <module>
C = AGNES(dataset, dist_avg, 3)
File "C:/各种东西练习/1/4.py", line 62, in AGNES
Mi.append(dist(i, j))
File "C:/各种东西练习/1/4.py", line 39, in dist_avg
return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))
File "C:/各种东西练习/1/4.py", line 39, in <genexpr>
return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))
File "C:/各种东西练习/1/4.py", line 28, in dist
t = t + math.pow(a[i]-b[i], 2)
TypeError: must be real number, not DataFrame

``````

• 写回答

#### 2条回答默认 最新

• CSDN专家-HGJ 2022-02-11 20:02
关注

改成np.power()试试：

``````import numpy as np
a=np.array([1,2,3,4])
b=np.array([2])
print(np.power(a,b))

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论 编辑记录

• 系统已结题 3月22日
• 已采纳回答 3月14日
• 创建了问题 2月11日

#### 悬赏问题

• ¥15 纯C++ 简单图色对比 灵敏度低的问题
• ¥15 麒麟ARM机器安装chromium浏览器
• ¥15 grbl 限位开关初始遮挡怎么处理？
• ¥15 输入网址无法跳转，如何解决？(关键词-CONNECT)
• ¥15 kubekey离线安装k8s及kubesphere报错
• ¥15 avalonia开发海康SDK怎么在linux实现预览？
• ¥15 keil5运行结果报错如下该怎么办
• ¥300 New-API新增渠道调试
• ¥20 zookeeper单服务器集群搭建，2888和2890端口没有监听
• ¥15 电梯与AGV小车,modbus转HTTP ,.