gpt4 book ai didi

python - 类型错误 : 'bool' object is not subscriptable Python 3

转载 作者:行者123 更新时间:2023-12-01 02:54:40 24 4
gpt4 key购买 nike

我收到以下错误:

TypeError                                 Traceback (most recent call last)
C:\Users\levanim\Desktop\Levani Predictive\cosinesimilarity1.py in <module>()
39
40 for i in meowmix_nearest_neighbors.index:
---> 41 top_ten = pd.DataFrame(similarity_matrix.ix[i,]).sort([i],
ascending=False[1:6]).index.values
42 meowmix_nearest_neighbors.ix[i,:] = top_ten
43
TypeError: 'bool' object is not subscriptable

以下代码。我是 Python 新手,不太清楚如何更改语法(如果它是 python 3 语法问题)。有人遇到这种情况吗?我认为这与 ascending=False[1:6] 部分有关,并且花了一些时间将我的头撞在墙上。希望这是一个简单的修复,但还不够了解

import numpy as np
import pandas as pd
from scipy.spatial.distance import cosine


enrollments = pd.read_csv(r'C:\Users\levanim\Desktop\Levani
Predictive\smallsample.csv')

meowmix = enrollments.fillna(0)

meowmix.ix[0:5,0:5]

def getCosine(x,y) :
cosine = np.sum(x*y) / (np.sqrt(np.sum(x*x)) * np.sqrt(np.sum(y*y)))
return cosine

print("done creating cosine function")

similarity_matrix = pd.DataFrame(index=meowmix.columns,
columns=meowmix.columns)
similarity_matrix = similarity_matrix.fillna(np.nan)

similarity_matrix.ix[0:5,0:5]
print("done creating a matrix placeholder")


for i in similarity_matrix.columns:
for j in similarity_matrix.columns:
similarity_matrix.ix[i,j] = getCosine(meowmix[i].values,
meowmix[j].values)

print("done looping through each column and filling in placeholder with
cosine similarities")


meowmix_nearest_neighbors = pd.DataFrame(index=meowmix.columns,
columns=['top_'+str(i+1) for i in
range(5)])

meowmix_nearest_neighbors = meowmix_nearest_neighbors.fillna(np.nan)

print("done creating a nearest neighbor placeholder for each item")


for i in meowmix_nearest_neighbors.index:
top_ten = pd.DataFrame(similarity_matrix.ix[i,]).sort([i],
ascending=False[1:6]).index.values
meowmix_nearest_neighbors.ix[i,:] = top_ten

print("done creating the top 5 neighbors for each item")

meowmix_nearest_neighbors.head()

最佳答案

而不是

    top_ten = pd.DataFrame(similarity_matrix.ix[i,]).sort([i], 
ascending=False[1:6]).index.values

使用

    top_ten = pd.DataFrame(similarity_matrix.ix[i,]).sort([i], 
ascending=False), [1:6]).index.values

(即在 False 之后插入 ),。)

Falsesort() 方法参数的值,含义是“不按升序排列”,即。 e.需要降序。因此,您需要使用 ) 终止 sort() 方法参数列表,然后分隔 DataFrame第一个参数> 来自第二个的构造函数,带有 ,

[1:6] 是 DataFrame 构造函数的第二个参数(用于结果帧的索引)

关于python - 类型错误 : 'bool' object is not subscriptable Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337101/

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