![](/img/trans.png)
[英]how to fetch/extract the names of dataframes from a list of dataframes in a for-loop to use it inside the same for-loop?
[英]If-statement with list inside for-loop over same list
我将所有对的相似性得分添加到列表中。
data = []
for i1, i2 in list:
data.append([i1, i2, cosine_similarity([X[df.index.get_loc(i1)]],[X[df.index.get_loc(i2)]]).ravel()[0]])
但是,我只需要追加非零的分数即可。
我放入了if语句,但是由于它不是int类型,因此会产生错误。
for i1, i2 in list:
if [cosine_similarity([X[df.index.get_loc(i1)]], [X[df.index.get_loc(i2)]])] > 0:
data.append([i1, i2, cosine_similarity([X[df.index.get_loc(i1)]], [X[df.index.get_loc(i2)]]).ravel()[0]])
有什么办法仅在迭代过程中仅附加非零吗?
条件迭代的一般模式是(a for a in b if a)
。 将计算结果放入帮助器函数中以提高可读性,这应该可以工作:
def calc_sim(X, df, i1, i2):
return cosine_similarity([X[df.index.get_loc(i1)]],
[X[df.index.get_loc(i2)]])
data = [(i1, i2, sim)
for (i1, i2, sim) in ((i1, i2, calc_sim(X, df, i1, i2))
if sim > 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.