计算 pandas 数据帧行对中的匹配数

Count number of matches in pairs of pandas dataframe rows

我一直在尝试计算一行数据框中的不同值与其他行中的列值匹配的次数并提供输出。为了说明,我有一个数据框(df_testing)如下:

import pandas as pd
df_testing = pd.DataFrame([
    [0,23,1, 3, 4,2],
    [1,33,3, 2, 4,3],
    [2,40,1, 2, 4,2]],
    columns=['SN','Age',  'Col_1', 'Col_2', 'Col_3','Col_4'])

which gives the following table:

Index|SN |Age |Col_1|Col_2|Col_3|Col_4|
---- |---|----|---- |-----|-----|-----|
0    |0  |23  |1    |3    |4    |2    |
1    |1  |33  |3    |2    |4    |3    |
2    |2  |40  |1    |2    |4    |2    |

我正在计算 Col_1 到 Col_4 中值的行之间完全匹配的数量。例如,第 0 行与第 1 行只有一个匹配项(Col_3 中的 4 和 4),而第 0 行与第 2 行有 3 个匹配项(1,1;4,4 和 2,2)。因此,我的目标是输出(最好是 csv 文件),其中包含所有唯一对,如下所示(最右边的列显示匹配的计数数):

SN_A|SN_B|Age_A|Age_B|Matched_Count|
----|----|-----|-----|-------------|
0   |1   |23   |33   |    1        |
0   |2   |23   |40   |    3        |
1   |2   |33   |40   |    2        |

我认为这需要一个循环,到目前为止,由于我不够熟练,我设法做到的与我想要实现的目标相去甚远。我以某种方式设法得到了印有以下几行的唯一对:

length = len(df_testing)
for x in range(length):
    # print(x)
    for y in range(2,6,1):
        a= df_testing.iloc[x][y]
        for m in range(length):
            if m>x:
                b= df_testing.iloc[m][y]
                print(a,b)

This just prints out the respective values in pairs (e.g. 1,3; 1,1;3,2 etc).

因此,我们将不胜感激生成如上所示输出的任何指导。

您可以使用 itertools.combinations、字典理解和 Series 构造函数:

from itertools import combinations

df2 = df_testing.set_index(['SN', 'Age'])
out = (pd.Series({(*a, *b): (df2.loc[a]==df2.loc[b]).sum()
                  for a,b in combinations(df2.index, r=2)
                  })
         .rename_axis(('SN_A', 'Age_A', 'SN_B', 'Age_B'))
         .reset_index(name='Matched_Count')
       )

输出:

   SN_A  Age_A  SN_B  Age_B  Matched_Count
0     0     23     1     33              1
1     0     23     2     40              3
2     1     33     2     40              2