Skip to content
Advertisement

Count number of matches in pairs of pandas dataframe rows

I have been trying to count the number of times different values in a row of dataframe matches with column-wise values in other rows and provide an output. To illustrate, I have a dataframe (df_testing) as follows:

JavaScript

I am looking to count the number of exact matches among rows for values in Col_1 to Col_4. For example, Row 0 has just one match with Row 1 (4 and 4 in Col_3) while Row 0 has 3 matches with Row2 (1,1; 4,4, and 2,2). As such, I am aiming for an output (preferably csv file) with all unique pairs like below (the rightmost column shows the number of counts matched):

JavaScript

I am thinking that this would require a loop and so far, due to my lack of proficiency, what I have managed to do is nowhere near what I want to achieve. I have somehow managed to get the unique pairs printed with the following lines:

JavaScript

Hence, any guidance to produce the output like shown above will be highly appreciated.

Advertisement

Answer

You could use itertools.combinations, a dictionary comprehension and the Series constructor:

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement