Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas compare 3 columns and output the result if count more than 1

I have 3 columns with value either A, B or C I want to compare these 3 columns and give output which value have more than 1 counts. If the count is tie then the output will be "-"

Input:

    | col1  | col2  | col3  |
    |-------|-------|-------|
    | A     | A     | B     |
    | A     | B     | B     |
    | C     | B     | C     |
    | A     | B     | C     |

Output:

    | col1  | col2  | col3  | Result|
    |-------|-------|-------|-------|
    | A     | A     | B     | A     |
    | A     | B     | B     | B     |
    | C     | B     | C     | C     |
    | A     | B     | C     | -     |
like image 510
Jimmy Avatar asked Feb 02 '26 01:02

Jimmy


1 Answers

Let's try with Counter to get the most common element:

from collections import Counter

def most_common():
    for s in df.to_numpy():
        k, v = Counter(s).most_common(1)[0] 
        yield '-' if v == 1 else k

df['Result'] = list(most_common())

  col1 col2 col3 Result
0    A    A    B      A
1    A    B    B      B
2    C    B    C      C
3    A    B    C      -
like image 81
Shubham Sharma Avatar answered Feb 04 '26 14:02

Shubham Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!