我有一个apply函数,它遍历索引列表,将其插入scikit-learn KNN模型,并返回两个大小为[[n的列表(邻居距离和邻居索引)。 (想象一下这是用于电影推荐系统的。)我想将这些结果添加到新的DF。
例如:如果我的函数迭代3个索引,并且n-neighbor参数为5,我应该得到一个2列且长度为3x5 = 15的DataFrame。但是目前,我的脚本将整个列表追加到一行,如下所示。
这是我的代码。
电影
是具有输入索引的DF。testDF = pd.DataFrame()
def get_distances_indices(index):
distances, indices = model_knn.kneighbors(data[index], n_neighbors=6)
distances = pd.Series(distances.flatten().tolist())
indices = pd.Series(indices.flatten().tolist())
return indices, distances
testDF[['index','distance']] = testDF.append(movies.apply(lambda row: get_distances_indices(row['index']), axis=1).apply(pd.Series),ignore_index=True)
感谢您的帮助。我是一个初学者,看到有文章说在此处使用Apply将有助于加快获取邻居列表的过程。
为简单起见,这是一个可复制的示例:我只希望列表/系列以垂直顺序而不是水平顺序显示。
testDF = pd.DataFrame()
moviesData = {'movie': ['The Big Whale', 'Stack Underflow'], 'index': [3, 99]}
movies = pd.DataFrame(data=moviesData)
def get_distances_indices(index):
list1 = [51, 700, 999]
list2 = [.2, .3, .4]
df2 = pd.Series(list1)
df3 = pd.Series(list2)
return df2,df3
testDF[['index','distance']] = movies.apply(lambda row: get_distances_indices(row['index']), axis=1).apply(pd.Series)
testDF.head()
我有一个apply函数,它遍历一个索引列表,将其插入scikit-learn KNN模型,并返回两个n大小的列表(邻居距离和邻居索引)。 (想象一下这是用于...