对 Pandas 列中的元素应用函数,分组到另一列

Sus*_*ant 11 python distance pandas

我有一个包含几列的数据集。现在我想要的是基本上根据特定列(“名称”)计算分数,但在“id”列上分组。

         _id      fName        lName    age
0       ABCD     Andrew       Schulz    
1       ABCD    Andreww                  23
2       DEFG       John          boy
3       DEFG      Johnn          boy     14
4       CDGH        Bob        TANNA     13
5       ABCD.     Peter        Parker    45
6       DEFGH     Clark          Kent    25
Run Code Online (Sandbox Code Playgroud)

所以我正在寻找的是,对于相同的 id,我是否得到了类似的条目,因此我可以根据阈值分数值删除这些条目。就像这里,如果我为 col“fName”运行它。我应该能够根据分数阈值减少这个数据框:

         _id      fName        lName   age
0       ABCD     Andrew       Schulz    23
2       DEFG       John          boy    14
4       CDGH        Bob        TANNA    13
5       ABCD      Peter       Parker    45
6       DEFG      Clark         Kent    25
Run Code Online (Sandbox Code Playgroud)

我打算使用pyjarowinkler。如果我有两个独立的列(没有所有分组的东西)要检查,这就是我使用它的方式。

    df['score'] = [distance.get_jaro_distance(x, y) for x, y in zip(df['name_1'],df['name_2'])]
    df = df[df['score'] > 0.87]
Run Code Online (Sandbox Code Playgroud)

有人可以建议这样做的pythonic和快速方法吗

更新

因此,我尝试为此使用记录链接库。我最终得到了一个包含一对相似索引的数据帧,称为“匹配”。现在我只想基本上结合数据。

    # Indexation step
    indexer = recordlinkage.Index()
    indexer.block(left_on='_id')
    candidate_links = indexer.index(df)

    # Comparison step
    compare_cl = recordlinkage.Compare()
    compare_cl.string('fName', 'fName', method='jarowinkler', threshold=threshold, label='full_name')

    features = compare_cl.compute(candidate_links, df)

    # Classification step
    matches = features[features.sum(axis=1) >= 1]
    print(len(matches))
Run Code Online (Sandbox Code Playgroud)

这是比赛的样子:

index1   index2          fName
0           1             1.0
2           3             1.0
Run Code Online (Sandbox Code Playgroud)

我需要有人建议一种方法,以从相似行中获取数据的方式组合相似的行

小智 1

只是想消除对您的问题的一些疑问。由于声誉较低,无法在评论中清除它们。

就像这里,如果我为 col“fName”运行它。我应该能够根据分数阈值减少此数据框:

所以基本上你的函数会返回包含每组中第一行的 DataFrame(按 ID)?这将产生上面列出的结果 DataFrame。

         _id      fName        lName   age
0       ABCD     Andrew       Schulz    23
2       DEFG       John          boy    14
4       CDGH        Bob        TANNA    13
Run Code Online (Sandbox Code Playgroud)