【问题标题】:How to find the similarities between combinations in a df?如何找到df中组合之间的相似性?
【发布时间】:2020-10-06 14:03:53
【问题描述】:

我有以下问题:我想显示每个实体组合共享的相似字符串的数量。我的数据在实体和字符串的数量上远大于此,但这是一个简化的案例:

Entity,String
X,A
X,B
Z,C
Z,A
Y,A
X,C

结果看起来像:

X:   3 (it has 3 distinct strings A/B/C)
Y:   1 (string A)
Z:   2 (strings A/C)
XY:  1 (X & Y only share string A)
XZ:  2 (X & Z share strings A & C)
YZ:  1 (X & Z only share string A)
XYZ: 1 (X,Y,Z only share string A)

通常,如果我只有两个要比较的实体,我会进行合并并计算两者的数量。但现在我拥有的实体比这个简化的案例还要多,有多种组合。

我怎样才能最简单地为实体组合中的共享字符串编写这种类型的不同计数?

【问题讨论】:

    标签: python pandas performance dataframe combinations


    【解决方案1】:
    In [273]: df                                                                                                                                                                                                                                                                     
    Out[273]: 
      entity string
    0      X      A
    1      X      B
    2      Z      C
    3      Z      A
    4      Y      A
    5      X      C
    
    In [274]: for c in range(1, len(df.entity.unique()) +1): 
         ...:     for combo in itertools.combinations(df.entity.unique(), c): 
         ...:         dfs = (df[df.entity == e] for e in combo) 
         ...:         a = set.intersection(*(set(f.string.unique()) for f in dfs)) 
         ...:         print(''.join(combo), len(a)) 
         ...:                                                                                                                                                                                                                                                                        
    X 3
    Z 2
    Y 1
    XZ 2
    XY 1
    ZY 1
    XZY 1
    

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      相关资源
      最近更新 更多