gpt4 book ai didi

python - 调试类型错误: unhashable type: 'numpy.ndarray'

转载 作者:行者123 更新时间:2023-11-30 22:59:09 25 4
gpt4 key购买 nike

我正在研究 kmeans 聚类。我在网络上一些可用引用的帮助下写下了代码,但是当我运行此代码时,它会引发错误:

    Traceback (most recent call last):
File "clustering.py", line 16, in <module>
ds = df[np.where(labels==i)]
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1678, in __getitem__
return self._getitem_column(key)
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1685, in _getitem_column
return self._get_item_cache(key)
File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 1050, in _get_item_cache
res = cache.get(item)
TypeError: unhashable type: 'numpy.ndarray'

虽然,许多以前的线程都出现相同的错误,但没有单一的解决方案可以在我的程序中处理此错误。我该如何调试这个错误?

我使用的代码:

from sklearn import cluster
import pandas as pd

df = [
[0.57,-0.845,-0.8277,-0.1585,-1.616],
[0.47,-0.14,-0.5277,-0.158,-1.716],
[0.17,-0.845,-0.5277,-0.158,-1.616],
[0.27,-0.14,-0.8277,-0.158,-1.716]]

df = pd.DataFrame(df,columns= ["a","b","c","d", "e"])

# df = pd.read_csv("cleaned_remove_cor.csv")

k = 3
kmeans = cluster.KMeans(n_clusters=k)
kmeans.fit(df)
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
from matplotlib import pyplot
import numpy as np

for i in range(k):
# select only data observations with cluster label == i
ds = df[np.where(labels==i)]
# plot the data observations
pyplot.plot(ds[:,0],ds[:,1],'o')
# plot the centroids
lines = pyplot.plot(centroids[i,0],centroids[i,1],'kx')
# make the centroid x's bigger
pyplot.setp(lines,ms=15.0)
pyplot.setp(lines,mew=2.0)
pyplot.show()

我的 DataFrame 的形状是 (8127x600)

最佳答案

我尝试过,这对我有用,将 pandas df 转换为 numpy 矩阵:

df = df.as_matrix(columns= ["a","b","c","d", "e"])

关于python - 调试类型错误: unhashable type: 'numpy.ndarray' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com