Python 循环中的重复行追加到内部

Python 循环中的重复行追加到内部,python,pandas,dataframe,append,Python,Pandas,Dataframe,Append,我在函数内的for循环中遇到问题。我正在计算单词向量列表的余弦距离。对于每个向量,我计算余弦距离,然后将其作为新列附加到数据帧。问题是有几个模型,所以我将模型1中的单词向量与其他模型中的单词向量进行比较 这意味着并非所有模型中都存在某些词语。在本例中,我对KeyError使用了一个异常,并允许循环继续运行而不抛出错误。如果发生这种情况,我还要求在数据帧中添加一个0值。这会导致索引重复,我无法继续前进。代码如下: from scipy.spatial.distance import cosine

我在函数内的for循环中遇到问题。我正在计算单词向量列表的余弦距离。对于每个向量,我计算余弦距离,然后将其作为新列附加到数据帧。问题是有几个模型,所以我将模型1中的单词向量与其他模型中的单词向量进行比较

这意味着并非所有模型中都存在某些词语。在本例中,我对KeyError使用了一个异常,并允许循环继续运行而不抛出错误。如果发生这种情况,我还要求在数据帧中添加一个0值。这会导致索引重复,我无法继续前进。代码如下:

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

def cosines(model1, model2, model3, model4, model5, model6, model7, words):
    df = pd.DataFrame()

    model = [model2, model3, model4, model5, model6, model7]

    for i in model:
        for j in words:
            try:
                cos = 1 - cosine(model1.wv[j], i.wv[j])
                print(f'cosine for model1 vs {i.name:} {1 - cosine(model1[j], i[j])}')
                tempdf = pd.DataFrame([cos], columns=[f'{j}'], index=[f'{i.name}'])
                #print(tempdf)
                df = pd.concat([df, tempdf], axis=0)
            except KeyError:
                print(word not present at {i.name}')
                ke_tempdf = pd.DataFrame([0], columns=[f'{j}'], index=[f'{i.name}'])
                df = pd.concat([df, ke_tempdf], axis=0)
                pass
    return df
但是,该函数对每个KeyError都有效-它不是在一行中添加一个0,而是创建一个值为0的新的重复项。使用两个单词,这复制了数据帧,但最终目标是拥有一个包含许多单词的列表。生成的数据帧如下所示:

        word1       word2
model1  0.000000    NaN
model1  NaN         0.761573
model2  0.000000    NaN
model2  NaN         0.000000
model3  0.000000    NaN
model3  NaN         0.000000
model4  0.245140    NaN
model4  NaN         0.680306
model5  0.090268    NaN
model5  NaN         0.662234
model6  0.000000    NaN
model6  NaN         0.709828

正如您所看到的,对于每个不存在的单词,它不是将0添加到现有模型行(NaN),而是添加一个编号为0的新行。它应该是:
model1、0、0.76等,而不是重复的行。非常感谢您的帮助,谢谢

没有您的模型对象,我无法完全测试它,但我认为这可以解决您的问题:

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

def cosines(model1, model2, model3, model4, model5, model6, model7, words):
    df = pd.DataFrame()

    model = [model2, model3, model4, model5, model6, model7]

    for i in model:
        cos_dict = {}
        for j in words:
            try:
                cos_dict[j] = 1 - cosine(model1.wv[j], i.wv[j])
                print(f'cosine for model1 vs {i.name:} {1 - cosine(model1[j], i[j])}')
            except KeyError:
                print(f'word not present at {i.name}')
                cos_dict[j] = 0
                
        tempdf = pd.DataFrame.from_dict(cos_dict, orient='columns')
        tempdf.index = [f'{i.name}']
        
        df = pd.concat([df, tempdf])
            
    return df

它在内部循环的字典中收集每个模型的单词值,在外部循环中只将它们固定到完整的数据帧中一次。

这非常有效-谢谢!仅供参考,索引必须用标量值指定,因此在tempdf=pd.DataFrame_处从_dict抛出一个错误-我用以下方法更正了这一错误:tempdf=pd.DataFrame([cos_dict])tempdf.index=[f'{I.name}']df=pd.concat([df,tempdf])其余部分按预期工作-再次感谢!对任何感兴趣的人来说,我使用的另一个肮脏的解决方法是使用df.concat([df,tempdf],axis=1)-索引是正确的,但列是根据它来自的模型复制的。。。然后,我将复制的列折叠如下:df=df.groupby(df.columns,axis=1).max().fillna(0)-这同样有效!万一有人想要像我这样的垃圾替代品!!实际上,关于索引和数据都需要列表的问题,您是对的。在我的测试代码中,我确实做到了这一点,但在转录过程中遗漏了这一点。:)