【问题标题】:Count number of matches in pairs of pandas dataframe rows计算熊猫数据框行对中的匹配数
【发布时间】:2022-01-24 13:24:54
【问题描述】:

我一直在尝试计算一行数据框中的不同值与其他行中的按列值匹配的次数并提供输出。为了说明,我有一个数据框(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 行(1,1;4,4 和 2,2)有 3 个匹配项。因此,我的目标是输出(最好是 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).

因此,我们将非常感谢任何生成如上所示输出的指导。

【问题讨论】:

    标签: python pandas match


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 2015-01-28
      • 1970-01-01
      • 2017-12-29
      • 2017-11-03
      • 1970-01-01
      • 2019-08-20
      相关资源
      最近更新 更多